Coding Knowledge Center
Perl
Conditional (if/elsif/else) |
if () {
} elsif () {
} else {
}
endif
Construct for if/else if/else statements.
Conditional (switch block) |
sub do_switch {
my $some_number = shift;
my $status = "true";
$_ = $some_number;
SWITCH: {
# $_ = 1
/^1$/ && do {
# do something
last SWITCH;
};
# $_ = 2
/^2$/ && do {
# do something
last SWITCH;
};
# $_ = 3
/^3$/ && do {
# do something
last SWITCH;
};
# no number matched (default)
$status = "false";
}
return $status;
}
The above example presents a nice switch-type statement for Perl, which does not natively provide this construct.
Constants |
# CONSTANTS - DATE
use constant DAYS_OF_THE_WEEK => ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"];
use constant MONTHS => ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
my $date_day = DAYS_OF_THE_WEEK->[0];
my $date_month = MONTHS->[3];
1) Set the constant array values.
2) Access the constant array values.
$date_day equals Sun
$date_month equals Apr
Execute |
perl -e [script]
Executes the script [script].
Does not need the "shebang!" line if executed in this manner.
File (read) |
my $file = "myfile.txt";
open (FILE, "$file");
while (<FILE>) {
chomp ($_);
print "$_\n";
}
close (FILE);
Opens a file (myfile.txt) for reading and then prints it's contents.
Functions (pass parameter to function) |
main();
sub main() {
function1("world");
}
sub function1 {
my $hello = shift;
print $hello";
}
Pass a parameter to a function.
The above example would pass "world" to function1 and then print the passed in value "world" now set in $hello.
Functions (return value from function) |
main();
sub main() {
my $value = function1();
print $value;
}
sub function1 {
return 1
}
Return a value from a function.
The above example would return 1 from function1 and then print "1" which is set in $value.
Hashes (multi-dimensional - sort index) |
my $myhash{$key1}{$key2}++;
foreach $key1 ( sort keys (%myhash)) {
foreach $key2 ( sort { $key2{$a} <=> $key2{$b} } keys %{ $myhash{$key1} } ) {
$value = $myhash{$key1}{$key2});
}
}
Above is an example of a multidimensional hash in action.
Hashes (multi-dimensional - sort string) |
my $myhash{$key1}{$key2}++;
foreach $key1 ( sort keys (%myhash)) {
foreach $key2 ( sort { $a cmp $b } keys %{ $myhash{$key1} } ) {
$value = $myhash{$key1}{$key2});
}
}
Another example this time sorting string keys.
Hashes (set hash) |
%hash = (
"element1" => "value1",
"element2" => "value2"
);
Here the keys and values of the hash are being explicitly set.
The metedata element1 & element2 are the keys while value1 & value2 are the values of those keys.
Hostname |
use Sys::Hostname;
my $hostname = hostname();
Sets $hostname to the current server's name.
Interpreter |
#!/usr/bin/perl
Always the first line of script.
Specifies to interpret this script using the perl interpreter, using the interpreter at the supplied location.
Login (get) |
my $login = getlogin();
Gets the executing users login name.
Mail ("mail" program.) |
my $receipients = "my list of receipients goes here";
my $subject = "my subject goes here";
my $body = "my body goes here";
open(MM, qq(|/bin/mail -s "$subject" $receipients));
print MM $body;
close MM;
Send email using the "mail" program.
Mail ("sendmail" program) |
my $mail_file = "mail.txt";
my $receipients = "my list of receipients goes here";
my $subject = "my subject goes here";
my $body = "my body goes here";
open (MAILFILE,">$mail_file") or die "Could not write $mail_file!";
print MAILFILE "To: " . $receipients . "\n";
print MAILFILE "Subject: $subject\n";
print MAILFILE "$body\n";
close (MAILFILE);
system ("/usr/sbin/sendmail -t < $mail_file");
Send mail using sendmail.
Modules (find) |
perl -MFile::Find -le 'find sub{push @m, $File::Find::name if/\.pm$/}, $_ for @INC; print for @m'
Lists all the installed perl modules on the current system.
Options (parse) |
for (my $argc = 0; $argc <= $#ARGV; $argc++) {
if ($ARGV[$argc]) {
$opt = $ARGV[$argc];
$opt =~ s/--//; # Get rid of 2 dashes
$opt =~ s/-//; # Get rid of 1 dash
$opt = substr($opt,0,1); # cut the first char
}
if ($opt eq 'c') {
$arg_cron = "true";
} elsif ($opt eq 'e') {
$arg_event = $ARGV[++$argc];
$check_event = check_event($arg_event);
if ($check_event eq "false") {
usage();
exit 1;
}
} elsif ($opt eq 'h') {
usage();
exit 0;
} elsif ($opt eq 'l') {
$arg_lp = $ARGV[++$argc];
$check_lp = check_lp($arg_lp);
if ($check_lp eq "false") {
error("Print $arg_lp not found.", 105);
}
} else {
usage();
exit 1;
}
}
The above example parses out all possible options.
Snippets (email) |
$body = "time: $cron_time" . "\n" . $cron_subject . "\n";
open(MM, qq(|/bin/mail -s "$subject" $receipient));
print MM $body;
close MM;
#============#
open (MAILFILE,">msg.txt") or error("Could not write email!", 100);
print MAILFILE "To: " . $user . "\n";
print MAILFILE "Subject: testing mail\n";
print MAILFILE "It works!\n";
close (MAILFILE);
system ("/usr/sbin/sendmail -t < msg.txt");
Various mail script examples
Snippets (file) |
open (FILE, "$file");
while (<FILE>) {
chomp ($_);
}
close (FILE);
Various file snippets
Snippets (hashes) |
$cars{$make}{$model}++;
foreach my $make ( sort keys (%cars)) {
my $carcnt = "";
foreach my $model ( sort { $model{$a} <=> $model{$b} } keys %{ $cars{$make} } ) {
$carcnt = sprintf("%0.5d", $cars{$make}{$model});
print "$make $model = $carcnt\n";
}
}
#============#
%hash = (
"element1" => "value1",
"element2" => "value2"
);
Various hash functions
Snippets (option parsing) |
for (my $argc = 0; $argc <= $#ARGV; $argc++) {
if ($ARGV[$argc]) {
$opt = $ARGV[$argc];
$opt =~ s/--//; # Get rid of 2 dashes
$opt =~ s/-//; # Get rid of 1 dash
$opt = substr($opt,0,1); # cut the first char
}
if ($opt eq 'c') {
$arg_cron = "true";
} elsif ($opt eq 'e') {
$arg_event = $ARGV[++$argc];
$check_thing = check_thingy($arg_event);
if ($check_thing eq "false") {
usage();
exit 1;
}
} elsif ($opt eq 'h') {
usage();
exit 0;
} elsif ($opt eq 'l') {
$arg_lp = $ARGV[++$argc];
$check_lp = check_lp($arg_lp);
if ($check_lp eq "false") {
error("Print $arg_lp not found.", 105);
}
} else {
usage();
exit 1;
}
}
Various option parsing snippets
Snippets (Spreadsheet::WriteExcel)) |
use Spreadsheet::WriteExcel;
my $workbook = Spreadsheet::WriteExcel->new("new_file.xls") or die "Could not create file $!";
my $worksheet = $workbook->addworksheet("sheetA");
my ($x, $y);
foreach my $fields ( sort keys (%records)) {
$x = 0;
my ($name, $title, $salary) = split(/_/, $fields,3);
$worksheet->write($y, $x++, $name);
$worksheet->write($y, $x++, $title);
$worksheet->write($y, $x++, $salary);
$y++;
}
$workbook->close();
Various Excel module snippets
Usage (subroutine) |
sub usage {
print "\nusage: $prog [-c] [-e entity] [-h] [-l printer_id]\n\n";
print "Options:\n";
print " -c flag indicating this program is being run as a cron job";
print " -e entity run program on a single specified entity\n";
print " -h usage information\n";
print " -l printer_id print to a specified printer id\n";
print "\n";
}
The above example gives a nice template to use for a usage function.