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:

    ...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)

    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)