Perl

[top] shebang!

#!/usr/bin/perl
Always the first line of script.
Specifies to interpret this script using the perl interpreter.


[top] Execute

perl -e [script]
Executes the script [script].
Does not need the "shebang!" line if executed in this manner.


[top] Conditional Statements

Switch

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.


[top] 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"]; 
Set the constant array values.

my $date_day   = DAYS_OF_THE_WEEK->[0];
my $date_month = MONTHS->[3];
Access the constant array values.

$date_day = Sun
$date_month = Apr


[top] Find Modules

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.


[top] 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.

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.


[top] getlogin()

my $login = getlogin();
Gets the executing users login name.


[top] 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.

Multi-dimensional Hash
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.

Multi-dimensional Hash
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.


[top] hostname()

use Sys::Hostname;
my $hostname = hostname();
Sets $hostname to the current server's name.


[top] Mail

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 mail using mail.
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.


[top] 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.


[top] Read File

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.


[top] Usage

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.