Code University

      "Where tuition is free!"

News | Images | Contact     
  • Home
  • Coding KC
  • Scripts
  • Software
  • Templates
  • Tutorials
  • About
 

Coding Knowledge Center

Perl


Page Contents
[X] CLOSE

Conditional

  • Conditional (if/elsif/else)
  • Conditional (switch block)

Constants

  • Constants

Execute

  • Execute

File

  • File (read)

Functions

  • Functions (pass parameter to function)
  • Functions (return value from function)

Hashes

  • Hashes (multi-dimensional - sort index)
  • Hashes (multi-dimensional - sort string)
  • Hashes (set hash)

Hostname

  • Hostname

Interpreter

  • Interpreter

Login

  • Login (get)

Mail

  • Mail ("mail" program.)
  • Mail ("sendmail" program)

Modules

  • Modules (find)

Options

  • Options (parse)

Snippets

  • Snippets (email)
  • Snippets (file)
  • Snippets (hashes)
  • Snippets (option parsing)
  • Snippets (Spreadsheet::WriteExcel))

Usage

  • Usage (subroutine)
Toggle Page Contents
Conditional (if/elsif/else)Copy  To New Window  Top ^
if () { } elsif () { } else { } endif
Construct for if/else if/else statements.



Conditional (switch block)Copy  To New Window  Top ^
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.



ConstantsCopy  To New Window  Top ^
# 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



ExecuteCopy  To New Window  Top ^
perl -e [script]
Executes the script [script]. Does not need the "shebang!" line if executed in this manner.



File (read)Copy  To New Window  Top ^
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)Copy  To New Window  Top ^
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)Copy  To New Window  Top ^
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)Copy  To New Window  Top ^
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)Copy  To New Window  Top ^
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)Copy  To New Window  Top ^
%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.



HostnameCopy  To New Window  Top ^
use Sys::Hostname; my $hostname = hostname();
Sets $hostname to the current server's name.



InterpreterCopy  To New Window  Top ^
#!/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)Copy  To New Window  Top ^
my $login = getlogin();
Gets the executing users login name.



Mail ("mail" program.)Copy  To New Window  Top ^
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)Copy  To New Window  Top ^
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)Copy  To New Window  Top ^
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)Copy  To New Window  Top ^
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)Copy  To New Window  Top ^
$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)Copy  To New Window  Top ^
open (FILE, "$file"); while (<FILE>) { chomp ($_); } close (FILE);
Various file snippets



Snippets (hashes)Copy  To New Window  Top ^
$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)Copy  To New Window  Top ^
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))Copy  To New Window  Top ^
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)Copy  To New Window  Top ^
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.
Technologies
  • Introduction
  • Awk
  • Bash
  • Cron
  • CSH
  • CSS
  • CVS
  • FTP
  • FTPS
  • HTML
  • JavaScript
  • KSH
  • Linux
  • Linux (Debian)
  • Linux (LPIC 101-102)
  • Linux/Unix
  • Mac OS X
  • MySQL
  • Oracle
  • Perl
  • PGP
  • PHP
  • Sed
  • SQLite
  • SSH/SCP/SFTP
  • Telnet
  • UNIX
  • Windows
Resources
  • CodeIgniter - MVC Framework
  • HowtoForge - Linux Tutorials
  • Linux Today - Linux News
  • Lxer - Linux News Feed
  • Monsterb - Linux, Podcasting
  • MySQL - Databasing
  • Perl - Programming
  • PHP - Programming
  • Systhread - Admin & Programming
  • W3Schools - Web Tutorials
About

Code University contains a wealth of technical information aimed at the computer sciences.


 
Home | Coding KC | Scripts | Software | Templates | Tutorials | About
Top ^
 
© 2007-2012 Code University| Disclaimer
Website template by Arcsin