Perl - Example Code

Example Code

In older versions of Perl, one would write the Hello World program as:

print "Hello World!\n";

In later versions, which support the say statement, one can also write it as:

use 5.010; say "Hello World!";

Good Perl practices require more complex programs to add the use strict; and use warnings; pragmas, leading into something like:

use strict; use warnings; print "Hello World!\n";

Here is a more complex Perl program, that counts down the seconds up to a given threshold:

#!/usr/bin/perl use strict; use warnings; use Time::HiRes qw(sleep time); use POSIX qw; use IO::Handle; my $delay = shift(@ARGV); STDOUT->autoflush(1); { my $start = time; my $end = $start + $delay; my $last_printed; while ((my $t = time) < $end) { my $new_to_print = POSIX::floor($end - $t); if (!defined($last_printed) or $new_to_print != $last_printed) { $last_printed = $new_to_print; print "Remaining $new_to_print/$delay", ' ' x 40, "\r"; } sleep(0.1); } } print "\n";

The perl interpreter can also be used for one-off scripts on the command line. The following example as invoked from an sh-compatible shell such as Bash translates the string "Bob" in all files ending with .txt in the current directory to "Robert":

$ perl -i.bak -lp -e 's/Bob/Robert/g' *.txt

Read more about this topic:  Perl

Famous quotes containing the word code:

    Motion or change, and identity or rest, are the first and second secrets of nature: Motion and Rest. The whole code of her laws may be written on the thumbnail, or the signet of a ring.
    Ralph Waldo Emerson (1803–1882)

    Hollywood keeps before its child audiences a string of glorified young heroes, everyone of whom is an unhesitating and violent Anarchist. His one answer to everything that annoys him or disparages his country or his parents or his young lady or his personal code of manly conduct is to give the offender a “sock” in the jaw.... My observation leads me to believe that it is not the virtuous people who are good at socking jaws.
    George Bernard Shaw (1856–1950)