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:

    Wise Draco comes, deep in the midnight roll
    Of black artillery; he comes, though late;
    In code corroborating Calvin’s creed
    And cynic tyrannies of honest kings;
    He comes, nor parlies; and the Town, redeemed,
    Gives thanks devout; nor, being thankful, heeds
    The grimy slur on the Republic’s faith implied,
    Which holds that Man is naturally good,
    And—more—is Nature’s Roman, never to be
    scourged.
    Herman Melville (1819–1891)

    ...I had grown up in a world that was dominated by immature age. Not by vigorous immaturity, but by immaturity that was old and tired and prudent, that loved ritual and rubric, and was utterly wanting in curiosity about the new and the strange. Its era has passed away, and the world it made has crumbled around us. Its finest creation, a code of manners, has been ridiculed and discarded.
    Ellen Glasgow (1873–1945)