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:

    Faultless honesty is a sine qua non of business life. Not alone the honesty according to the moral code and the Bible. When I speak of honesty I refer to the small, hidden, evasive meannesses of our natures. I speak of the honesty of ourselves to ourselves.
    Alice Foote MacDougall (1867–1945)

    Acknowledge your will and speak to us all, “This alone is what I will to be!” Hang your own penal code up above you: we want to be its enforcers!
    Friedrich Nietzsche (1844–1900)