Intro:
Perl is a mature, open-source, cross-platform language that takes the best features from other languages such as C, awk, sed, tcl, sh, and BASIC, among others. It's motto is "TMTOWTDI" (There's More Than One Way To Do It): Perl is flexible and allows you to work in the way you prefer.
e.g. extracting links from a string into a list:
@links = m/<A[^>]+?HREF\s*=\s*["']?([^'" >]+?)[ '"]?>/sig;
e.g. copy $my_string to $my_other_string, lowercase all letters, remove "," and "."
($my_other_string = $my_string) =~ tr/A-Z,./a-z/d;
e.g. exchanging variables without using temp variables:
($a, $b) = ($b, $a);
e.g. implementing "cat" in one line of Perl:
print <>;
e.g. implementing hl7_rdr in awk vs. perl using a module
#!/bin/sh
USAGE="USAGE: $0 data_file"
if [ ! -f "$1" -a "$1" != "-" ]; then
echo "$USAGE" >&2
exit 2
fi
cat $1 | /usr/ucb/tr "\015" "\012" |
nawk -F'|' '{
if ( $1 == "" ) {
startfield = 2;
}
else {
startfield = 1;
}
tmpstr = "";
for(j=startfield;j<=NF;j++) {
if ( length(tmpstr) + length($j) < 80 ) {
if ( j == startfield )
tmpstr = sprintf("%s",$j);
else
tmpstr = sprintf("%s|%s",tmpstr,$j);
}
else {
print tmpstr;
tmpstr = sprintf(" |%s",$j);
}
}
print tmpstr;
}'
vs.
#!/usr/bin/perl
use Text::Wrap qw(wrap $columns $break);
$columns = 80;
$break = qr/(?=\|)/;
$initial_tab = "";
$subsequent_tab = " ";
$/ = "\r"; # input record separator
while (<>) {
tr/\n/\r/; # convert newlines to carriage returns
$_ = wrap($initial_tab, $subsequent_tab, $_);
tr/\r/\n/; # back to newlines
print;
}
e.g. delete all .log files in current dir that have a modification time older than 3 days
for (glob("*.log")) {
unlink if (-f && -M _ > 3);
}
This would be a significantly longer program in most other languages.
e.g. ftp a new NetConfig over to sitedoc's pending dir on makali
use Net::FTP;
$ftp = Net::FTP->new("makali.carenet.org", Debug => 1);
$ftp->login("USER","PASS");
$ftp->cwd("/hci/root3.7.1P/sitedoc/iig/pending");
$ftp->put("NetConfig.new");
$ftp->quit;
Example: switch statement
SWITCH: {
if (/^abc/) { $abc = 1; last SWITCH; }
if (/^def/) { $def = 1; last SWITCH; }
if (/^xyz/) { $xyz = 1; last SWITCH; }
$nothing = 1;
}
or
SWITCH: {
$abc = 1, last SWITCH if /^abc/;
$def = 1, last SWITCH if /^def/;
$xyz = 1, last SWITCH if /^xyz/;
$nothing = 1;
}
or
SWITCH: {
/^abc/ && do { $abc = 1; last SWITCH; };
/^def/ && do { $def = 1; last SWITCH; };
/^xyz/ && do { $xyz = 1; last SWITCH; };
$nothing = 1;
}
or
SWITCH: {
/^abc/ && do {
$abc = 1;
last SWITCH;
};
/^def/ && do {
$def = 1;
last SWITCH;
};
/^xyz/ && do {
$xyz = 1;
last SWITCH;
};
$nothing = 1;
}
or
SWITCH: {
/^abc/ and $abc = 1, last SWITCH;
/^def/ and $def = 1, last SWITCH;
/^xyz/ and $xyz = 1, last SWITCH;
$nothing = 1;
}
or
SWITCH: for ($where) {
/In Card Names/ && do { push @flags, '-e'; last; };
/Anywhere/ && do { push @flags, '-h'; last; };
/In Rulings/ && do { last; };
die "unknown value for form variable where: `$where'";
}