Perl Tutorial: Based On A Tutorial by Nano Gough
Perl Tutorial: Based On A Tutorial by Nano Gough
• LAZINESS:
– The quality that makes you go to great effort to
reduce overall energy expenditure.
– makes you want to re-use other people's code
• IMPATIENCE:
– The anger you feel when the computer is being lazy.
– makes you get things done quickly (rapid prototyping)
and efficiently (optimize code)
• HUBRIS:
– Excessive pride.
– makes you want to show off (code sharing) and write
(and maintain) programs that other people won't want
to say bad things about.
Running Perl
$a = 5; $b=7;
$a = $b; # Assign $b to $a ($a=7)
$a += $b; or $a=$a+b; # Add $b to $a ($a=12)
$a -= $b; or $a=$a-$b; # Subtract $b from $a ($a=-2)
Concatenation Interpolation
$a = 'Monday'; $b='Tuesday'; # double quotations may include vars
$c=$a . ' ' . $b; $c= “$a $b”;
$c= 'Monday Tuesday'; # c is now 'Monday Tuesday';
$d= $a . ' and ' . $b; $d= “$a and $b”;
$d=‘Monday and Tuesday’; # $d is now 'Monday and Tuesday';
Testing
Numbers
$a == $b # Is $a numerically equal to $b?
# don’t use $a=$b as this will not compare but just assign $b to $a
$a != $b # Is $a numerically unequal to $b?
$a<$b / $a>$b # Is $a less than/greater than $b
$a <=$b / $a >=$b # Is a less than or equal to/ g.t or eq to $b
#################################
#if $a is equal to 1 AND $b is equal to red: print Colour 1 is red
If(($a==1) || ($b eq ‘red’)){print “Colour $a is $b\n”;}
Arrays
Initialize an array/set to null
@colours=();
Functions push and pop
#assign elements to array @colours
@colours=(“red”,”blue”,”yellow”);
#use push function to add an element to the end of array
push(@colours,”green”);
#colours now contains:
“red”,”blue”,”yellow”,”green”
#use pop function to remove an element from the end of array
pop(@colours);
#colours now contains
“red”, “blue”, “yellow”
#Functions shift and unshift
@colours=(“red”,”blue”,”yellow”);
$new_el=“green”;
#use unshift to append $new_el to start of array
unshift(@colours, $new_el);
@colours is now:
“green”,“red”,”blue”,”yellow”
@colours = (“red”,”blue”,”yellow”);
print “$colours[0]”; #prints: red
}
Split
$sentence =~ /the/
#The RE is case sensitive, so if $sentence = "The quick brown fox"; then
the above match will be false.
Example
$sentence= “the red and white dress”;
$sentence =~ s/red/blue;
# $sentence is now = “the blue and white dress”
Some on-line Perl Tutorials:
http://www.comp.leeds.ac.uk/Perl/start.html
http://archive.ncsa.uiuc.edu/General/Training/PerlIntro/
http://www.pageresource.com/cgirec/index2.htm
Text books:
Perl cookbook; Tom Christiansen and Nathan Torkington