SlideShare uma empresa Scribd logo
1 de 176
Perl Development Sample Courseware Created October 2008 © Garth Gilmour 2008
Overview ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Introduction to Perl History and Basic Concepts © Garth Gilmour 2008
Introduction to Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Versions of Perl and Competitors ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Comparing Perl, Python and Ruby © Garth Gilmour 2008 Perl  Python Ruby Documentation ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦  ♦ ♦ ♦  Library Support ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ OO Support ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Power ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Approachability ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Ease of Mastery ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ C / C++ Interop ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Java / .NET Interop ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Web Frameworks ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦
Common Applications of Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 Scripts Core language features Programs Strict module Subroutines References Applications Best Practises Named Parameters Modules and classes
Learning Programming in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Common Applications of Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Declaring Variables in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008 Sigil Description $ Scalar variable - holds a single number string or reference @ Array variable - a sequence of one or more scalars % Hash variable - a maps of keys and values (both scalars) Reference - used to specify a scalar holds a memory address & Function - used to specify a symbol is a function name * Typeglob - used for manipulating symbol tables (advanced)
Variables and Barewords ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Variables and Symbol Tables ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 Symbol Table Typeglob $fred = 12; @fred = (12,13,14); %fred = (k1 =>12, k2 => 14); sub fred { return 101; } Name Link fred Others… Type Link $ @ % &
Perl Comments ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Using Heredoc Comments © Garth Gilmour 2008 $myvar = << &quot;THE_END&quot;; More than prince of cats, I can tell you. O, he is the courageous captain of compliments. He fights  as you sing prick-song, keeps time, distance, and proportion; rests me his minim rest, one, two, and the  third in your bosom: the very butcher of a silk button,  a duellist, a duellist; a gentleman of the very first  house, of the first and second cause: ah, the  immortal passado! the punto reverso! the hay!  THE_END print &quot;--- START DATA ---&quot;, $myvar, &quot;--- END DATA ---&quot;;
The Perl Language and Modules ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
The Strict Module ,[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008 Example Declaration Description use strict ‘vars’ User defined variables must be declared by:   ♦  Using the  ‘my’ or ‘our’ functions ♦  Prefixing the variable with a package name  use strict ‘refs’ Symbolic references (an obsolete feature) are not allowed use strict ‘subs’ Barewords are treated as syntax errors, rather than being interpreted as subroutine names or unquoted strings
Basic Programming The Core Perl Syntax © Garth Gilmour 2008
Introducing Scalar Variables ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Scalar Variables and Operators ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Operators Commonly Used in Perl © Garth Gilmour 2008 Description Number Version String Version Addition $var1 + $var2 $var1 . $var2 Equality $var1 == $var2 $var1 eq $va2 Ordered Comparison >, <, <=, >= lt, gt, le, ge Power Of $var1 ** 3 $var1 x 3 Bitwise Comparison &, |, ^ (NB work differently for numbers and strings) Logical &&, ||, ! and, or, not (Lower precedence) Conditional $var1 = $var2 ? 12 : 14; Range 1..4 ‘ D’ .. ‘Z’
© Garth Gilmour 2008 $num1 = 42; $num2 = &quot;42&quot;; $result = $num1 + $num2; print &quot;adding numbers gives $result&quot;, &quot;&quot;x2; $result = $num1 . $num2; print &quot;adding strings gives $result&quot;, &quot;&quot;x2; $result = $num2 ** 3; print &quot;42 to the power of 3 is $result&quot;, &quot;&quot;x2; $result = $num1 x 3; print &quot;42 concatenated with itself three times is $result&quot;, &quot;&quot;x2; if($num1 == $num2) { print '$num1 and $num2 are equal as numbers',&quot;&quot;x2; } if($num1 eq $num2) { print '$num1 and $num2 are equal as strings',&quot;&quot;x2; }
String Values in Detail  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 $var1 = &quot;abc&quot;; $var2 = 123; $var3 = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]; print 'Values are $var1, $var2 and $var3 '; print &quot;Values are $var1, $var2 and $var3 &quot;; $path = `set path`; print &quot;Value of path environment variable is: $path&quot;; Values are $var1, $var2 and $var3 Values are abc, 123 and ARRAY(0x225e28)  Value of path environment variable is: PATH=c:dk1.5.0_05in;C:erlitein;C:erlin;c:ubyin;C:INDOWSystem32;C:INDOWS;C:INDOWSystem32bem;
What is Truth in Perl? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 $var1 = &quot;0&quot;;  # The string &quot;0&quot; counts as false $var2 = &quot;&quot;;  # The empty string also counts as false $var3 = &quot;AB&quot;;  # Other string values are true $var4 = -12;  # Other numerical values are true $var5;  # Undefined values are false $var6 = undef();  # Values set to undef are false printTruth('$var1',$var1); printTruth('$var2',$var2); printTruth('$var3',$var3); printTruth('$var4',$var4); printTruth('$var5',$var5); printTruth('$var6',$var6); undef($var4);  # Release storage space for var1 so it becomes undefined printTruth('$var4',$var4); sub printTruth { my ($varName,$varValue) = @_; if($varValue) { print &quot;$varName is true&quot;; } else { print &quot;$varName is false&quot;; } }
Special Scalar Variables ,[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008 Variable Name Description $] The version of Perl supported by this interpreter $0 The name of the file containing the current script $^O The name of the operating system $_ The current item (used in input, output and loops) $/ The line separator used when reading text (default it newline)
Special Scalar Variables © Garth Gilmour 2008 print &quot;This is verson $] of Perl&quot;; print &quot;Running on the $^O operating system&quot;; print &quot;The current script is $0 &quot;; @myarray = (&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;,&quot;gh&quot;); print &quot;Elements are:&quot;; foreach(@myarray) { print &quot; $_ &quot;; } This is verson 5.008008 of Perl Running on the MSWin32 operating system The current script is C:erlpecialScalars.pl  Elements are:   ab    cd    ef    gh
Reading Text Into a Scalar Variable ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 open(INPUT,&quot;MuchAdoAboutNothing.txt&quot;); $count = 1; foreach(<INPUT>) { print(&quot;$count: $_&quot;); $count++; } 1:  Much Ado About Nothing 2:  A comedy by William Shakespear 3:   4:  Act 1, Scene 1 5:  Before LEONATO'S house. 6:   Enter LEONATO, HERO, and BEATRICE, with a Messenger 7:   8:  LEONATO  9:   I learn in this letter that Don Peter of Arragon 10:   comes this night to Messina.
Conditionals and Iteration in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 print &quot;Enter a number&quot;; $number = <STDIN>; chomp($number); if($number < 10) { print &quot;$number is less than 10&quot;; } elsif($number < 20) { print &quot;$number is less than 20&quot;; } elsif($number < 30) { print &quot;$number is less than 30&quot;; } else { print &quot;$number is greater than 30&quot;; } unless($number % 2 == 0) { print &quot;$number is odd&quot;; } Enter a number 17 17 is less than 20 17 is odd
Conditionals and Iteration in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 print &quot;Enter a positive number&quot;; $max = <STDIN>; chomp($max); if($max <= 0) { die(&quot;Number must be positive!&quot;); } print &quot;Demo of while loop&quot;; print &quot;Numbers from 0 to $max are:&quot;; $count = 0; while($count <= $max) { print &quot;$count&quot;; $count++; } print &quot;Demo of do..while loop&quot;; print &quot;Numbers from 0 to $max are:&quot;; $count = 0; do { print &quot;$count&quot;; $count++; } while($count <= $max); print &quot;Demo of until loop&quot;; print &quot;Numbers from 0 to $max are:&quot;; $count = 0; until($count > $max) { print &quot;$count&quot;; $count++; }  print &quot;Demo of do..until loop&quot;; print &quot;Numbers from 0 to $max are:&quot;; $count = 0; do { print &quot;$count&quot;; $count++; }until($count > $max); print &quot;Demo of for loop v1&quot;; print &quot;Numbers from 0 to $max are:&quot;; for($count=0; $count<= $max; $count++) { print &quot;$count&quot;; } print &quot;Demo of for each loop v3&quot;; print &quot;Numbers from 0 to $max are:&quot;; for(0..$max) { print &quot;$_&quot;; }
Conditionals and Iteration in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Basic Perl I/O Using the Console and Files © Garth Gilmour 2008
Basic Perl I/O ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Testing File Paths ,[object Object],[object Object],[object Object],© Garth Gilmour 2008 File Test Operator Description -e File exists -r File is readable -w File is writable -z File has zero size -s Returns file size -T File is a text file -B File is a binary file -S File is a socket
Opening and Reading From Files ,[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008 Function Description open(HANDLE, “myfile.txt”) open(HANDLE, “<myfile.txt”) Open file for reading open(HANDLE, “>myfile.txt”) Open file for writing (truncating if necessary) open(HANDLE, “>>myfile.txt”) Open file for appending open(HANDLE, “+<myfile.txt”) Open file for reading and updating
Opening and Reading From Files ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 open(INPUT,&quot;input.txt&quot;); open(OUTPUT,&quot;>output.txt&quot;); $count = 0; while($line = <INPUT>) { print OUTPUT ++$count, &quot;&quot;, $line; } print &quot;Processed $count lines&quot; This short interval was sufficient to determine d'Artagnan on the part he was to take.  It was one of those events which decide the life of a man; it was a choice between the king and the cardinal--the choice made, it must be persisted in.  To fight, that was to disobey the law, that was to risk his head, that was to make at one blow an enemy of a minister more powerful than the king himself.  All this young man perceived, and yet, to his praise we speak it, he did not hesitate a second.  Turning towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to correct your words, if you please.  You said you were but three, but it appears to me we are four.&quot; 1 This short interval was sufficient to determine d'Artagnan on the 2 part he was to take.  It was one of those events which decide the 3 life of a man; it was a choice between the king and the 4 cardinal--the choice made, it must be persisted in.  To fight, 5 that was to disobey the law, that was to risk his head, that was 6 to make at one blow an enemy of a minister more powerful than the 7 king himself.  All this young man perceived, and yet, to his 8 praise we speak it, he did not hesitate a second.  Turning 9 towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to 10 correct your words, if you please.  You said you were but three, 11 but it appears to me we are four.&quot;
© Garth Gilmour 2008 open(INPUT, '<', &quot;input.txt&quot;); open(OUTPUT, '>', &quot;output.txt&quot;); $count = 0; while($line = <INPUT>) { print OUTPUT ++$count, &quot;&quot;, $line; } print &quot;Processed $count lines&quot; This short interval was sufficient to determine d'Artagnan on the part he was to take.  It was one of those events which decide the life of a man; it was a choice between the king and the cardinal--the choice made, it must be persisted in.  To fight, that was to disobey the law, that was to risk his head, that was to make at one blow an enemy of a minister more powerful than the king himself.  All this young man perceived, and yet, to his praise we speak it, he did not hesitate a second.  Turning towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to correct your words, if you please.  You said you were but three, but it appears to me we are four.&quot; 1 This short interval was sufficient to determine d'Artagnan on the 2 part he was to take.  It was one of those events which decide the 3 life of a man; it was a choice between the king and the 4 cardinal--the choice made, it must be persisted in.  To fight, 5 that was to disobey the law, that was to risk his head, that was 6 to make at one blow an enemy of a minister more powerful than the 7 king himself.  All this young man perceived, and yet, to his 8 praise we speak it, he did not hesitate a second.  Turning 9 towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to 10 correct your words, if you please.  You said you were but three, 11 but it appears to me we are four.&quot;
© Garth Gilmour 2008 open($input, '<', &quot;input.txt&quot;); open($output, '>', &quot;output.txt&quot;); $count = 0; while($line = <$input>) { print $output ++$count, &quot;&quot;, $line; } print &quot;Processed $count lines&quot; This short interval was sufficient to determine d'Artagnan on the part he was to take.  It was one of those events which decide the life of a man; it was a choice between the king and the cardinal--the choice made, it must be persisted in.  To fight, that was to disobey the law, that was to risk his head, that was to make at one blow an enemy of a minister more powerful than the king himself.  All this young man perceived, and yet, to his praise we speak it, he did not hesitate a second.  Turning towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to correct your words, if you please.  You said you were but three, but it appears to me we are four.&quot; 1 This short interval was sufficient to determine d'Artagnan on the 2 part he was to take.  It was one of those events which decide the 3 life of a man; it was a choice between the king and the 4 cardinal--the choice made, it must be persisted in.  To fight, 5 that was to disobey the law, that was to risk his head, that was 6 to make at one blow an enemy of a minister more powerful than the 7 king himself.  All this young man perceived, and yet, to his 8 praise we speak it, he did not hesitate a second.  Turning 9 towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to 10 correct your words, if you please.  You said you were but three, 11 but it appears to me we are four.&quot;
Opening and Reading From Files ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 open($input, '<', &quot;input.txt&quot;) or die &quot;Can't open input&quot;; open($output, '>', &quot;output.txt&quot;) or die &quot;Can't open output&quot;; $count = 0; while($line = <$input>) { print($output ++$count, &quot;&quot;, $line) or die &quot;Can't write to file&quot;; } print &quot;Processed $count lines&quot;; close($input) or die &quot;Can't close input&quot;; close($output) or die &quot;Can't close output&quot;;
File Handles and Globbing ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 @exampleDirectories = glob('..'); print &quot;Perl example files are: &quot;; foreach $dir (@exampleDirectories) { @perlFiles = glob($dir . '.pl'); foreach(@perlFiles) { #characters preceding a slash preceding #  letters ending in '.pl' m/.*(+pl)/; print &quot;$1 in $dir &quot;; } } Perl example files are:  arrayFunctions.pl in ..rrays  arraysAndLists.pl in ..rrays  days.pl in ..rrays  forEach.pl in ..rrays  fork.pl in ..oncurrency  threads.pl in ..oncurrency  customerDB.pl in ..atabases  arraysOfArrays.pl in ..ataStructures  checkingErrors.pl in ..iles  indirectHandles.pl in ..iles  basicHashes.pl in ..ashes  extraSyntax.pl in ..ashes
Arrays in Perl Creating and Using Lists © Garth Gilmour 2008
Introducing Arrays in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 $myarray[8] = &quot;string in 9th box&quot;; $myarray[10] = &quot;string in 11th box&quot;; $count = 0; foreach(@myarray) { print $count++,&quot;: $_&quot;; } 0:  1:  2:  3:  4:  5:  6:  7:  8: string in 9th box 9:  10: string in 11th box
Support for Arrays in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Support for Arrays in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 @tstArray = qw(abc def ghi jkl mno pqr); ($first) = @tstArray; ($a,$b,$c) = @tstArray; print &quot;First element is: $first&quot;; print &quot;First three elements are: $a $b $c&quot; First element is: abc First three elements are: abc def ghi
Special Features of Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Special Features of Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 @workDays = (&quot;Monday&quot;,&quot;Tuesday&quot;,&quot;Wednesday&quot;,&quot;Thursday&quot;,&quot;Friday&quot;); @weekendDays = qw(Saturday Sunday);  @days = (@workDays,@weekendDays);  $numDays = @days;  $firstDay = $days[0]; $lastDay = $days[$#days]; print &quot;There are $numDays days in a week&quot;; print &quot;$firstDay is the first day and $lastDay is the last day &quot;; print &quot;The other days are:&quot;; foreach $day (@days) { unless($day eq $firstDay or $day eq $lastDay) { print $day, &quot;&quot;; } } print &quot;The last four days are:&quot;; @lastDays = @days[3..6]; foreach $day (@lastDays) { print $day, &quot;&quot;; }
Iterating Over Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008 @myarray = qw(abc def ghi jkl); print &quot;Loop one&quot;; foreach $item (@myarray) { print &quot;&quot;,$item,&quot;&quot; ; } print &quot;Loop two&quot;; foreach (@myarray) { print &quot;&quot;,$_,&quot;&quot; ; } print &quot;Loop three&quot;; for $item (@myarray) { print &quot;&quot;,$item,&quot;&quot; ; } print &quot;Loop four&quot;; for (@myarray) { print &quot;&quot;,$_,&quot;&quot; ; }
Functions for Working With Arrays ,[object Object],[object Object],[object Object],© Garth Gilmour 2008 Function Name Description push Add a new box to the end of the array pop Remove a box from the end of the array unshift Add a new box to the start of the array shift Remove the first box in the array join Join all the values in the array into a string, separated by a delimiter split Create an array by splitting a string into a sequence of sub-strings, using a regular expression to specify the delimiter token(s)
© Garth Gilmour 2008 @myarray1 = qw(abc def ghi); $val1 = pop(@myarray1); print &quot;Just popped $val1, contents now:&quot;; foreach(@myarray1) { print &quot;$_&quot;; } push(@myarray1,&quot;zzz&quot;); print &quot;Just pushed zzz, contents now:&quot;; foreach(@myarray1) { print &quot;$_&quot;; } $val1 = shift(@myarray1); print &quot;Just shifted $val1, contents now:&quot;; foreach(@myarray1) { print &quot;$_&quot;; } unshift(@myarray1,&quot;AAA&quot;); print &quot;Just unshifted AAA, contents now:&quot;; foreach(@myarray1) { print &quot;$_&quot;; } Just popped ghi, contents now: abc def Just pushed zzz, contents now: abc def zzz Just shifted abc, contents now: def zzz Just unshifted AAA, contents now: AAA def zzz
Hashes in Perl Creating and Using Tables © Garth Gilmour 2008
Introducing Hashes in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 $myhash{'k1'} = &quot;abc&quot;; $myhash{'k2'} = 123; $myhash{'k3'} = &quot;def&quot;; $myhash{'k4'} = 456; foreach $key (keys %myhash) { print $key, &quot; indexes &quot;, $myhash{$key}, &quot;&quot;; } k2 indexes 123 k1 indexes abc k3 indexes def k4 indexes 456
Initializing a Hash ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],k5 indexes 789 k2 indexes abc k1 indexes 123 k3 indexes 456 k4 indexes def
Functions for Working With Hashes ,[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008 Function Name Description each Returns a list of two values representing a row in the hash exists Returns true if a specified entry exists in the hash keys Returns a list of all the keys in the hash values Returns a list of all the values in the hash delete Removes a row from the hash
© Garth Gilmour 2008 %myhash = ( k1 => 123, k2 => &quot;abc&quot;, k3 => 456, k4 => &quot;def&quot;, k5 => 789 ); print &quot;Keys are:&quot;; foreach $key (keys %myhash) { print &quot;&quot;, $key, &quot;&quot;; } print &quot;Values are:&quot;; foreach $value (values %myhash) { print &quot;&quot;, $value, &quot;&quot;; } print &quot;Entries are:&quot;; while (($key, $value) = each(%myhash)) { print &quot;$key indexes $value &quot;; } Keys are: k5 k2 k1 k3 k4 Values are: 789 abc 123 456 def Entries are: k5 indexes 789  k2 indexes abc  k1 indexes 123  k3 indexes 456  k4 indexes def
Special Syntax for Hashes ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 %tstHash = (&quot;k1&quot;,&quot;v1&quot;,&quot;k2&quot;,&quot;v2&quot;); print &quot;Original hash contents:&quot;; foreach(keys(%tstHash)) { print(&quot;$_ indexes &quot;,$tstHash{$_},&quot;&quot;); } @tstHash {&quot;k3&quot;,&quot;k4&quot;,&quot;k5&quot;,&quot;k6&quot;} = (111,222,333,444);  print &quot;Hash contents after insertions:&quot;; foreach(keys(%tstHash)) { print(&quot;$_ indexes &quot;,$tstHash{$_},&quot;&quot;); } ($var1,$var2,$var3) = @tstHash {&quot;k1&quot;,&quot;k2&quot;,&quot;k3&quot;}; print &quot;Values in scalars are $var1 $var2 and $var3&quot;; @elements = %tstHash; print &quot;Array contents:&quot;; foreach(@elements) { print &quot;$_ &quot;; } Original hash contents: k2 indexes v2 k1 indexes v1 Hash contents after insertions: k5 indexes 333 k2 indexes v2 k1 indexes v1 k6 indexes 444 k3 indexes 111 k4 indexes 222 Values in scalars are v1 v2 and 111 Array contents: k5 333 k2 v2 k1 v1 k6 444 k3 111 k4 222
Hashes of Anonymous Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 %results = ( dave => [54, 62, 73, 48], jane => [59, 67, 82, 70], fred => [92, 64, 59, 71] ); results dave jane fred 54 62 73 48 59 67 82 70 92 64 59 71
Hashes of Anonymous Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 %actors = ( &quot;george clooney&quot; => [&quot;Oceans 11&quot;, &quot;The Peacemaker&quot;,  &quot;O Brother Where Art Thou&quot;], &quot;harrison ford&quot;  => [&quot;Star Wars&quot;,&quot;Sabrina&quot;,&quot;Indiana Jones&quot;], &quot;robin williams&quot; => [&quot;Good Morning Vietnam&quot;,&quot;Hook&quot;,&quot;The Birdcage&quot;]     ); print &quot;The list of actors and their movies is: &quot;; foreach $actor (keys %actors) { print &quot;$actor starred in: &quot;; foreach $film(@{$actors{$actor}}) { print &quot;$film&quot;; } } The list of actors and their movies is:  robin williams starred in:  Good Morning Vietnam Hook The Birdcage harrison ford starred in:  Star Wars Sabrina Indiana Jones george clooney starred in:  Oceans 11 The Peacemaker O Brother Where Art Thou
Regular Expressions Part 1: Core Concepts © Garth Gilmour 2008
Introducing Regular Expressions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
The Syntax of Regular Expressions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Key Regex Concept No 1 ,[object Object],[object Object],[object Object],© Garth Gilmour 2008 A B C D E F G H I J K L M N O Match No 1 Match No 2 Match No 3 Match No 4 Match No 5
Key Regex Concept No 2 ,[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008 A B C D E f g h I J K L M N o p q r S T U V W X y z Match 1 Match 2 Match 3
Character Classes ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Shortcuts for Character Classes ,[object Object],[object Object],[object Object],© Garth Gilmour 2008 Perl Shortcut Description Character Class  Digit [0-9]  Non-Digit [^0-9]  Whitespace Character [ ]  Non Whitespace Character [^ ]  Word Character [a-zA-Z0-9_]  Non-Word Character [^a-zA-Z0-9_]
Specifying Multiplicities  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Specifying Points Within the Input ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Using Submatches Within a Regex ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 ABCdefGHIjklMNOpqrSTU [A-Z]{2} Matches: AB GH MN ST ABCdefGHIjklMNOpqrSTU [A-Z]{3} Matches: ABC GHI MNO STU ABCdefGHIjklMNOpqrSTU [A-Z]{3}[a-z] Matches: ABCd GHIj MNOp
© Garth Gilmour 2008 ABCdefGHIjklMNOpqrSTU [A-Z]+[a-z]+ Matches: ABCdef GHIjkl MNOpqr ABCdefGHIjklMNOpqrSTU ([A-Z]+)([a-z]+) Matches: ABCdef Group 1: ABC Group 2: def GHIjkl Group 1: GHI Group 2: jkl MNOpqr Group 1: MNO Group 2: pqr ABCdefGHIjklMNOpqrSTU [A-Za-z]+ Matches:   ABCdefGHIjklMNOpqrSTU
© Garth Gilmour 2008 ABCdefGHIjklMNOpqrSTU [A-Za-z]{5} Matches: ABCde fGHIj klMNO pqrST ABCdefGHIjklMNOpqrSTU ^[A-Za-z]{5} Matches: ABCde ABCdefGHIjklMNOpqrSTU [A-Za-z]{5}$ Matches: qrSTU ABCdefGHIjklMNOpqrSTU [A-Za-z]{5,8} Matches: ABCdefGH IjklMNOp rqSTU
Other Meta-Characters ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Regular Expressions Part 2: Perl Syntax © Garth Gilmour 2008
Regular Expressions in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 $data = &quot;ABCdefGHIjklMNOpqrSTUvwxYZA&quot;; $m1 = $data =~ m/[A-Z]/; if($m1) { print &quot;Match one is $&&quot;; } $m2 = $data =~ m/[A-Z]{2}/; if($m2) { print &quot;Match two is $&&quot;; } $m3 = $data =~ m/[A-Z]+/; if($m3) { print &quot;Match three is $&&quot;; } $m4 = $data =~ m/[^e]+/; if($m4) { print &quot;Match four is $&&quot;; } $m5 = $data =~ m/[A-Z]{3}[a-z]{2}/; if($m5) { print &quot;Match five is $&&quot;; } Match one is A Match two is AB Match three is ABC Match four is ABCd Match five is ABCde
© Garth Gilmour 2008 $m6 = $data =~ m/[A-Z]+[a-z]+/; if($m6) { print &quot;Match six is $&&quot;; } $m7 = $data =~ m/[A-Za-z]{9}/; if($m7) { print &quot;Match seven is $&&quot;; } $m8 = $data =~ m/.+/; if($m8) { print &quot;Match eight is $&&quot;; } $m9 = $data =~ m/^.{8}/; if($m9) { print &quot;Match nine is $&&quot;; } $m10 = $data =~ m/.{8}$/; if($m10) { print &quot;Match ten is $&&quot;; } Match six is ABCdef Match seven is ABCdefGHI Match eight is ABCdefGHIjklMNOpqrSTUvwxYZA Match nine is ABCdefGH Match ten is TUvwxYZA
© Garth Gilmour 2008 @groupOne = $data =~ m/[A-Z]{3}/g; print &quot;First group of matches are:&quot;; foreach(@groupOne) { print &quot;$_&quot;; } @groupTwo = $data =~ m/[a-z]{3}/g; print &quot;Second group of matches are:&quot;; foreach(@groupTwo) { print &quot;$_&quot;; } @groupThree = $data =~ m/.{4}/g; print &quot;Third group of matches are:&quot;; foreach(@groupThree) { print &quot;$_&quot;; } First group of matches are: ABC GHI MNO STU YZA Second group of matches are: def jkl pqr vwx Third group of matches are: ABCd efGH Ijkl MNOp qrST Uvwx
Regular Expressions in Perl ,[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008 Modifier Description g Finds all the matches in the string i Makes the pattern case-insensitive s Means ‘.’ matches new-line characters m Means ‘^’ and ‘$’ match substrings
Using Regular Expressions in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Using Regular Expressions in Perl © Garth Gilmour 2008 print &quot;Enter the email address:&quot;; chomp($email = <STDIN>); #easier to read version of  ([a-z]+([a-z]+)?)megacorp(com|ie|couk) $m = $email =~ m{^  #start of string (  #start of inner match 1 [a-z]+  #one or more lowercase letters ([a-z]+)?  #optionally a dot and letters (inner match 2) )  #end of inner match 1 megacorp  #company name NB need to escape array (com|ie|couk)  #possible domain names $  #end of string }x; if($m) { print &quot;Recognized email for $1 in domain $3&quot;; } else { print &quot;Invalid address!&quot;; }
Pattern Matching and Substitutions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 $test = &quot;aabbccddyzeeffgghhiijjkkllmmnnoo&quot;; # Replace all occurances of ff with FF $test =~ s/ff/FF/g; print $test , &quot;&quot;; # Replace any occurance of four characters at the start of the string with XX $test =~ s/^.{4}/XX/g; print $test , &quot;&quot;; # Replace any lower case characters with their upper case equivalents $test =~ s/([a-z])/uc($1)/eg; print $test , &quot;&quot;; aabbccddyzeeFFgghhiijjkkllmmnnoo XXccddyzeeFFgghhiijjkkllmmnnoo XXCCDDYZEEFFGGHHIIJJKKLLMMNNOO
Regular Expressions Part 3: Advanced Concepts © Garth Gilmour 2008
Regular Expressions - Advanced ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Non Greedy Matching ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 abcDEfghIJklm [a-zA-Z]+[A-Z]{2} abcDEfghIJ Matches: abcDE fghIJ [a-zA-Z]+?[A-Z]{2} [a-zA-Z]*[A-Z]{2} abcDEfghIJklm Matches: ab cDEfg hIJkl [a-zA-Z]*?[A-Z]{2}
Parenthesis Which Do Not Capture ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Modifying Just Part of the Pattern ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Matching Without Capturing ,[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008 Assertion Explanation (?= …) Looks ahead to see if a pattern occurs without capturing (?! …) Looks ahead to see if a pattern  does not  occur without capturing (?<= …) Looks behind to see if a pattern occurs without capturing (?<! …) Looks behind to see if a pattern  does not  occur without capturing
Building Regex Parts Dynamically ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Working With Unicode ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Working With Unicode ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Sample Unicode Properties © Garth Gilmour 2008 Unicode Property Description AHex True for ASCII characters used in hexadecimal numbers Alpha True if a character can be compared to others ea The East Asian width of a character (full, half or narrow) IDC Indicates if a character can only be used as the first in an identifier Math True if the character is used in describing mathematical expressions Lower Indicates if a character is a lowercase letter STerm Indicates if a character is used to terminate a sentence Term Indicates if a character is punctuation that terminates a unit WSpace Indicates if a character should be treated as whitespace during parsing
Unicode Properties in Expressions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Perl Subroutines Creating and Calling Functions © Garth Gilmour 2008
Introducing Subroutines ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 sub func { my($param1, $param2, $param3, $param4, $param5) = @_; print &quot;func called with:&quot;; print &quot;$param1&quot;; print &quot;$param2&quot;; print &quot;$param3&quot;; print &quot;$param4&quot;; print &quot;$param5&quot;; } func(&quot;abc&quot;,123,&quot;def&quot;,456,&quot;ghi&quot;); func called with: abc 123 def 456 ghi
Variable Declarations and Scoping ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Variable Declarations and Scoping ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 $var1 = &quot;ABC&quot;; $var2 = &quot;DEF&quot;; $var3 = &quot;GHI&quot;; print &quot;At start $var1, $var2 and $var3&quot;; func1(); print &quot;At end $var1, $var2 and $var3&quot;; sub func1 { my $var1 = &quot;JKL&quot;; local $var2 = &quot;MNO&quot;; our $var3; print &quot;In func1 $var1, $var2 and $var3&quot;; func2(); } sub func2 { print &quot;In func2 $var1, $var2 and $var3&quot;; } At start ABC, DEF and GHI In func1 JKL, MNO and GHI In func2 ABC, MNO and GHI At end ABC, DEF and GHI
Using Named Parameters ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 sub func { my %params = @_; print &quot;Parameter fred has value $params{'fred'}&quot;; print &quot;Parameter wilma has value $params{'wilma'}&quot;; print &quot;Parameter barney has value $params{'barney'}&quot;; } print &quot;---------- First Call ----------&quot;; @args1 = (&quot;fred&quot;,20,&quot;wilma&quot;,30,&quot;barney&quot;,40); func(@args1); print &quot;---------- Second Call ----------&quot;; @args2 = (fred => 50, wilma => 60, barney => 70); func(@args2); print &quot;---------- Third Call ----------&quot;; func(fred => 80, wilma => 90, barney => 100); ---------- First Call ---------- Parameter fred has value 20 Parameter wilma has value 30 Parameter barney has value 40 ---------- Second Call ---------- Parameter fred has value 50 Parameter wilma has value 60 Parameter barney has value 70 ---------- Third Call ---------- Parameter fred has value 80 Parameter wilma has value 90 Parameter barney has value 100
Subroutines and Recursion ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Subroutines and Recursion © Garth Gilmour 2008 sub recursion1 { until($_[0] == 0) { print &quot;$_[0] &quot;; $_[0]--; &recursion1; } } sub recursion2 { if(@_) { print(shift, &quot; &quot;); &recursion2; } } $val1 = 10; recursion1($val1); print &quot;&quot;; @val2 = qw(abc def ghi jkl); recursion2(@val2); 10 9 8 7 6 5 4 3 2 1  abc def ghi jkl
Anonymous Subroutines ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 Closures are cool! Closures are cool! Closures are cool! Closures are cool! Closures are cool! Closures are very cool! Closures are very cool! Closures are very cool! ab cd ef gh sub doTimes { for(1..$_[0]) { &{$_[1]}(); } } sub withMatches { for($_[0] =~ m/$_[1]/g) { &{$_[2]}($_); } } $ref = sub { print &quot;Closures are cool!&quot;; }; doTimes(5, $ref); doTimes(3, sub { print &quot;Closures are very cool!&quot;; }); withMatches(&quot;ab cd ef gh&quot;, &quot;[a-z]{2}&quot;, sub { print &quot;$_[0]&quot;; });
Error Handling Managing Error Conditions © Garth Gilmour 2008
Error Handling in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 eval { op1(); }; if($@) { print &quot;Code threw error: &quot;, $@; } sub op1 { op2(); } sub op2 { op3(); } sub op3 { die &quot;BOOM!&quot;; } eval { op1(); }; if($@) { print &quot;Error of severity &quot;, $@->{'severity'};  print &quot; thrown with message &quot;, $@->{'msg'}; } sub op1 { op2(); } sub op2 { op3(); } sub op3 { my %error = (msg => 'BOOM!', severity => 'fatal'); die error; }
References in Perl Using Memory Addresses © Garth Gilmour 2008
References in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 $var1 = 124; $ref1 = var1; print $ref1, &quot;&quot;; print &quot;Reference ref1 refers to value $$ref1&quot;; print &quot;Reference ref1 refers to value ${$ref1}&quot;; SCALAR(0x226d98) Reference ref1 refers to value 124 Reference ref1 refers to value 124
© Garth Gilmour 2008 @var2 = (&quot;abc&quot;,&quot;def&quot;,&quot;ghi&quot;,&quot;jkl&quot;); $ref2 = var2; print $ref2, “”; print &quot;Reference ref2 refers to array with contents: &quot;; foreach $val (@$ref2) { print &quot;$val &quot;; } print &quot;Reference ref2 refers to array with contents: &quot;; foreach $val (@{$ref2}) { print &quot;$val &quot;; } print &quot;First three elements in array pointed to by ref2 are: &quot;; @slice = @{$ref2}[0..2]; foreach $val (@slice) { print &quot;$val &quot;; } print &quot;First item is $$ref2[0]&quot;; print &quot;First item is ${$ref2}[0]&quot;; print &quot;First item is $ref2->[0]&quot;;
© Garth Gilmour 2008 ARRAY(0x226da4) Reference ref2 refers to array with contents: abc def ghi jkl  Reference ref2 refers to array with contents: abc def ghi jkl  First three elements in array pointed to by ref2 are: abc def ghi  First item is abc First item is abc First item is abc
© Garth Gilmour 2008 %var3 = (&quot;k1&quot;,&quot;xxx&quot;,&quot;k2&quot;,&quot;yyy&quot;,&quot;k3&quot;,&quot;zzz&quot;); $ref3 = var3; print &quot;Reference ref3 refers to hash with contents:&quot;; foreach $key (keys %$ref3) { print &quot;$key indexes $$ref3{$key}&quot;; } print &quot;Reference ref3 refers to hash with contents:&quot;; foreach $key (keys %{$ref3}) { print &quot;$key indexes $ref3->{$key}&quot;; } print &quot;Key k1 indexes $$ref3{'k1'} &quot;; print &quot;Key k1 indexes ${$ref3}{'k1'} &quot;; print &quot;Key k1 indexes $ref3->{'k1'} &quot;;
© Garth Gilmour 2008 Reference ref3 refers to hash with contents: k2 indexes yyy k1 indexes xxx k3 indexes zzz Reference ref3 refers to hash with contents: k2 indexes yyy k1 indexes xxx k3 indexes zzz Key k1 indexes xxx  Key k1 indexes xxx  Key k1 indexes xxx
References and Anonymous Data ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 $ref1 = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;,&quot;gh&quot;]; $ref2 = { k1 => 123, k2 => 456, k3 => 789 }; $ref3 = sub { return $_[0] + $_[1]; }; print $ref1, &quot;&quot;; print $ref2, &quot;&quot;; print $ref3, &quot;&quot;; print $ref1->[0], &quot;&quot;; print $ref2->{'k1'}, &quot;&quot;; print $ref3->(12,5), &quot;&quot;; ARRAY(0x225f88) HASH(0x226d80) CODE(0x18303f0) ab 123 17
References and Data Structures ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 @numerals = ( [100,&quot;C&quot;], [90,&quot;XC&quot;], [50,&quot;L&quot;], [40,&quot;XL&quot;], [10,&quot;X&quot;], [9,&quot;IX&quot;], [5,&quot;V&quot;], [4,&quot;IV&quot;], [1,&quot;I&quot;] ); print &quot;Enter the number to convert to a roman numeral...&quot;; $number = <STDIN>; chomp($number); foreach (@numerals) { my $decimal = $_->[0]; my $string = $_->[1]; my $times = int($number / $decimal); if($times > 0) { for(1..$times) { print $string; } $number = $number % $decimal; } }
© Garth Gilmour 2008 $ref1 = [ [&quot;abc&quot;,&quot;def&quot;,&quot;ghi&quot;], [&quot;jkl&quot;,&quot;mno&quot;,&quot;pqr&quot;], [&quot;stu&quot;,&quot;vwx&quot;,&quot;yza&quot;] ]; print &quot;Contents of 2d array are:&quot;; foreach(@{$ref1}) { print &quot;&quot;; foreach(@{$_}) { print &quot;$_ &quot;; } print &quot;&quot;; } Contents of 2d array are: abc def ghi  jkl mno pqr  stu vwx yza
© Garth Gilmour 2008 $ref = { k1 => { k4 => &quot;ab&quot;, k5 => &quot;cd&quot; }, k2 => { k6 => &quot;ef&quot;, k7 => &quot;gh&quot; }, k3 => { k8 => &quot;ij&quot;, k9 => &quot;kl&quot; } }; print $ref->{'k1'}->{'k4'}, &quot;&quot;; print $ref->{'k1'}->{'k5'}, &quot;&quot;; print $ref->{'k2'}->{'k6'}, &quot;&quot;; print $ref->{'k2'}->{'k7'}, &quot;&quot;; print $ref->{'k3'}->{'k8'}, &quot;&quot;; print $ref->{'k3'}->{'k9'}, &quot;&quot;; ab cd ef gh ij kl
Modules and Packages Creating Reusable Code © Garth Gilmour 2008
Modules and Code Reuse in Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Creating Perl Modules ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Creating Perl Modules ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 package Maths; require Exporter; our @ISA = (&quot;Exporter&quot;); @EXPORT = qw(add multiply subtract); sub add { return $_[0] + $_[1]; } sub divide { return $_[0] / $_[1]; } sub multiply { return $_[0] * $_[1]; } sub subtract { return $_[0] - $_[1]; } use Maths; print &quot;Calculations using our maths module:&quot;; print &quot;40 + 30 is: &quot;, add(40,30); print &quot;60 - 20 is: &quot;, subtract(60,20); print &quot;50 * 10 is: &quot;, multiply(50,10); # divide is not exported so it only works  #  if we qualify the namespace print &quot;40 / 10 is: &quot;, Maths::divide(40,10);
© Garth Gilmour 2008 package Maths; require Exporter; our @ISA = (&quot;Exporter&quot;); @EXPORT_OK = qw(add multiply subtract); sub add { return $_[0] + $_[1]; } sub divide { return $_[0] / $_[1]; } sub multiply { return $_[0] * $_[1]; } sub subtract { return $_[0] - $_[1]; } use Maths qw(add multiply subtract); print &quot;Calculations using our maths module:&quot;; print &quot;40 + 30 is: &quot;, add(40,30); print &quot;60 - 20 is: &quot;, subtract(60,20); print &quot;50 * 10 is: &quot;, multiply(50,10); # divide is not exported so it only works  #  if we qualify the namespace print &quot;40 / 10 is: &quot;, Maths::divide(40,10);
Extra Syntax for Modules ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Objects in Perl Support for Object Oriented Programming Concepts © Garth Gilmour 2008
Object Oriented Perl  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
Core Principles of OO Languages ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 Client Code Account Objects account1 account2 withdraw { … } display { … } withdraw { … } display { … }
© Garth Gilmour 2008 class Account: def __init__(self,id,balance): self.id = id self.balance = balance def withdraw(self, amount): self.balance -= amount def display(self): print &quot;Account with id&quot;, self.id, &quot;and balance&quot;, self.balance account1 = Account(&quot;AB12&quot;,30000) account2 = Account(&quot;CD34&quot;,45000) print &quot;----- Before Withdrawl -----&quot; account1.display() account2.display() account1.withdraw(250) account2.withdraw(500) print &quot;----- After Withdrawl -----&quot; account1.display() account2.display() ----- Before Withdrawl ----- Account with id AB12 and balance 30000 Account with id CD34 and balance 45000 ----- After Withdrawl ----- Account with id AB12 and balance 29750 Account with id CD34 and balance 44500 Constructor Class Declaration Creating Objects
© Garth Gilmour 2008 class Account def initialize(id, balance) @id = id @balance = balance end def withdraw(amount) @balance -= amount end def display() puts &quot;Account with id #{@id} and balance #{@balance}&quot; end end account1 = Account.new(&quot;AB12&quot;,30000) account2 = Account.new(&quot;CD34&quot;,45000) puts &quot;----- Before Withdrawl -----&quot; account1.display() account2.display() account1.withdraw(250) account2.withdraw(500) puts &quot;----- After Withdrawl -----&quot; account1.display() account2.display() ----- Before Withdrawl ----- Account with id AB12 and balance 30000 Account with id CD34 and balance 45000 ----- After Withdrawl ----- Account with id AB12 and balance 29750 Account with id CD34 and balance 44500 Class Declaration Constructor Creating Objects
Perl Syntax for Object Orientation ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],© Garth Gilmour 2008
© Garth Gilmour 2008 package Account; sub new { my $packageName = shift; my $data = {}; $data->{'id'} = shift; $data->{'balance'} = shift; bless $data, $packageName; } sub withdraw { my $data = shift; $data->{'balance'} -= $_[0]; } sub display { my $data = shift; print &quot;Account with id $data->{'id'} and balance $data->{'balance'}&quot;; } Packages double as classes Any method can be a constructor Anonymous hashes hold fields
© Garth Gilmour 2008 $account1 = Account->new(&quot;AB12&quot;,30000); $account2 = Account->new(&quot;CD34&quot;,45000); print &quot;----- Before Withdrawl -----&quot;; $account1->display(); $account2->display(); $account1->withdraw(250); $account2->withdraw(500); print &quot;----- After Withdrawl -----&quot;; $account1->display(); $account2->display(); ----- Before Withdrawl ----- Account with id AB12 and balance 30000 Account with id CD34 and balance
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)
Perl Development (Sample Courseware)

Mais conteúdo relacionado

Mais procurados

Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guidelineDhananjaysinh Jhala
 
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)Adair Dingle
 
Object-Oriented Design: Multiple inheritance (C++ and C#)
Object-Oriented Design: Multiple inheritance (C++ and C#)Object-Oriented Design: Multiple inheritance (C++ and C#)
Object-Oriented Design: Multiple inheritance (C++ and C#)Adair Dingle
 
XKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & ConstructsXKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & ConstructsNicolas Demengel
 
PL Lecture 02 - Binding and Scope
PL Lecture 02 - Binding and ScopePL Lecture 02 - Binding and Scope
PL Lecture 02 - Binding and ScopeSchwannden Kuo
 
Fusing Modeling and Programming into Language-Oriented Programming
Fusing Modeling and Programming into Language-Oriented ProgrammingFusing Modeling and Programming into Language-Oriented Programming
Fusing Modeling and Programming into Language-Oriented ProgrammingMarkus Voelter
 
PL Lecture 01 - preliminaries
PL Lecture 01 - preliminariesPL Lecture 01 - preliminaries
PL Lecture 01 - preliminariesSchwannden Kuo
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Featurestechfreak
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming ParadigmsJaneve George
 
Introduction to c_sharp
Introduction to c_sharpIntroduction to c_sharp
Introduction to c_sharpHEM Sothon
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1ppJ. C.
 
Building scalable and language independent java services using apache thrift
Building scalable and language independent java services using apache thriftBuilding scalable and language independent java services using apache thrift
Building scalable and language independent java services using apache thriftTalentica Software
 
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages Charitha Gamage
 

Mais procurados (20)

Create Your Own Language
Create Your Own LanguageCreate Your Own Language
Create Your Own Language
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guideline
 
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)
 
Lexing and parsing
Lexing and parsingLexing and parsing
Lexing and parsing
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
Object-Oriented Design: Multiple inheritance (C++ and C#)
Object-Oriented Design: Multiple inheritance (C++ and C#)Object-Oriented Design: Multiple inheritance (C++ and C#)
Object-Oriented Design: Multiple inheritance (C++ and C#)
 
XKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & ConstructsXKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & Constructs
 
PL Lecture 02 - Binding and Scope
PL Lecture 02 - Binding and ScopePL Lecture 02 - Binding and Scope
PL Lecture 02 - Binding and Scope
 
PDF Localization
PDF  LocalizationPDF  Localization
PDF Localization
 
Fusing Modeling and Programming into Language-Oriented Programming
Fusing Modeling and Programming into Language-Oriented ProgrammingFusing Modeling and Programming into Language-Oriented Programming
Fusing Modeling and Programming into Language-Oriented Programming
 
PL Lecture 01 - preliminaries
PL Lecture 01 - preliminariesPL Lecture 01 - preliminaries
PL Lecture 01 - preliminaries
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
 
Dost.jar and fo.jar
Dost.jar and fo.jarDost.jar and fo.jar
Dost.jar and fo.jar
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
6 data types
6 data types6 data types
6 data types
 
Introduction to c_sharp
Introduction to c_sharpIntroduction to c_sharp
Introduction to c_sharp
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1pp
 
Building scalable and language independent java services using apache thrift
Building scalable and language independent java services using apache thriftBuilding scalable and language independent java services using apache thrift
Building scalable and language independent java services using apache thrift
 
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
 

Destaque

Aerohive Configuration guide.
Aerohive Configuration guide. Aerohive Configuration guide.
Aerohive Configuration guide. armaan7139
 
CODE BLUE 2014 : Physical [In]Security: It’s not ALL about Cyber by Inbar Raz
CODE BLUE 2014 : Physical [In]Security: It’s not ALL about Cyber by Inbar RazCODE BLUE 2014 : Physical [In]Security: It’s not ALL about Cyber by Inbar Raz
CODE BLUE 2014 : Physical [In]Security: It’s not ALL about Cyber by Inbar RazCODE BLUE
 
Workshop on Cyber security
Workshop on Cyber security Workshop on Cyber security
Workshop on Cyber security Mehedi Hasan
 
CSE 2016 Future of Cyber Security by Matthew Rosenquist
CSE 2016 Future of Cyber Security by Matthew RosenquistCSE 2016 Future of Cyber Security by Matthew Rosenquist
CSE 2016 Future of Cyber Security by Matthew RosenquistMatthew Rosenquist
 
The Future of Cyber Security
The Future of Cyber SecurityThe Future of Cyber Security
The Future of Cyber SecurityStephen Lahanas
 
IT Security Awarenesss by Northern Virginia Community College
IT Security Awarenesss by Northern Virginia Community CollegeIT Security Awarenesss by Northern Virginia Community College
IT Security Awarenesss by Northern Virginia Community CollegeAtlantic Training, LLC.
 
ISO 27001 - information security user awareness training presentation -part 2
ISO 27001 - information security user awareness training presentation -part 2ISO 27001 - information security user awareness training presentation -part 2
ISO 27001 - information security user awareness training presentation -part 2Tanmay Shinde
 
DTS Solution - Building a SOC (Security Operations Center)
DTS Solution - Building a SOC (Security Operations Center)DTS Solution - Building a SOC (Security Operations Center)
DTS Solution - Building a SOC (Security Operations Center)Shah Sheikh
 
Information Security Awareness Training by Wilfrid Laurier University
Information Security Awareness Training by Wilfrid Laurier UniversityInformation Security Awareness Training by Wilfrid Laurier University
Information Security Awareness Training by Wilfrid Laurier UniversityAtlantic Training, LLC.
 
Building a Next-Generation Security Operation Center Based on IBM QRadar and ...
Building a Next-Generation Security Operation Center Based on IBM QRadar and ...Building a Next-Generation Security Operation Center Based on IBM QRadar and ...
Building a Next-Generation Security Operation Center Based on IBM QRadar and ...IBM Security
 
ISO 27001 - information security user awareness training presentation - Part 1
ISO 27001 - information security user awareness training presentation - Part 1ISO 27001 - information security user awareness training presentation - Part 1
ISO 27001 - information security user awareness training presentation - Part 1Tanmay Shinde
 
Cyber Security 101: Training, awareness, strategies for small to medium sized...
Cyber Security 101: Training, awareness, strategies for small to medium sized...Cyber Security 101: Training, awareness, strategies for small to medium sized...
Cyber Security 101: Training, awareness, strategies for small to medium sized...Stephen Cobb
 
SOC presentation- Building a Security Operations Center
SOC presentation- Building a Security Operations CenterSOC presentation- Building a Security Operations Center
SOC presentation- Building a Security Operations CenterMichael Nickle
 

Destaque (20)

Aerohive Configuration guide.
Aerohive Configuration guide. Aerohive Configuration guide.
Aerohive Configuration guide.
 
CODE BLUE 2014 : Physical [In]Security: It’s not ALL about Cyber by Inbar Raz
CODE BLUE 2014 : Physical [In]Security: It’s not ALL about Cyber by Inbar RazCODE BLUE 2014 : Physical [In]Security: It’s not ALL about Cyber by Inbar Raz
CODE BLUE 2014 : Physical [In]Security: It’s not ALL about Cyber by Inbar Raz
 
Chapter5ccna
Chapter5ccnaChapter5ccna
Chapter5ccna
 
6421 b Module-10
6421 b  Module-106421 b  Module-10
6421 b Module-10
 
Chapter3ccna
Chapter3ccnaChapter3ccna
Chapter3ccna
 
ccna
ccnaccna
ccna
 
Workshop on Cyber security
Workshop on Cyber security Workshop on Cyber security
Workshop on Cyber security
 
Chapter10ccna
Chapter10ccnaChapter10ccna
Chapter10ccna
 
US Pmp Overview 2008
US Pmp Overview 2008US Pmp Overview 2008
US Pmp Overview 2008
 
CSE 2016 Future of Cyber Security by Matthew Rosenquist
CSE 2016 Future of Cyber Security by Matthew RosenquistCSE 2016 Future of Cyber Security by Matthew Rosenquist
CSE 2016 Future of Cyber Security by Matthew Rosenquist
 
The Future of Cyber Security
The Future of Cyber SecurityThe Future of Cyber Security
The Future of Cyber Security
 
IT Security Awarenesss by Northern Virginia Community College
IT Security Awarenesss by Northern Virginia Community CollegeIT Security Awarenesss by Northern Virginia Community College
IT Security Awarenesss by Northern Virginia Community College
 
ISO 27001 - information security user awareness training presentation -part 2
ISO 27001 - information security user awareness training presentation -part 2ISO 27001 - information security user awareness training presentation -part 2
ISO 27001 - information security user awareness training presentation -part 2
 
DTS Solution - Building a SOC (Security Operations Center)
DTS Solution - Building a SOC (Security Operations Center)DTS Solution - Building a SOC (Security Operations Center)
DTS Solution - Building a SOC (Security Operations Center)
 
Information Security Awareness Training by Wilfrid Laurier University
Information Security Awareness Training by Wilfrid Laurier UniversityInformation Security Awareness Training by Wilfrid Laurier University
Information Security Awareness Training by Wilfrid Laurier University
 
Security Awareness Training by Fortinet
Security Awareness Training by FortinetSecurity Awareness Training by Fortinet
Security Awareness Training by Fortinet
 
Building a Next-Generation Security Operation Center Based on IBM QRadar and ...
Building a Next-Generation Security Operation Center Based on IBM QRadar and ...Building a Next-Generation Security Operation Center Based on IBM QRadar and ...
Building a Next-Generation Security Operation Center Based on IBM QRadar and ...
 
ISO 27001 - information security user awareness training presentation - Part 1
ISO 27001 - information security user awareness training presentation - Part 1ISO 27001 - information security user awareness training presentation - Part 1
ISO 27001 - information security user awareness training presentation - Part 1
 
Cyber Security 101: Training, awareness, strategies for small to medium sized...
Cyber Security 101: Training, awareness, strategies for small to medium sized...Cyber Security 101: Training, awareness, strategies for small to medium sized...
Cyber Security 101: Training, awareness, strategies for small to medium sized...
 
SOC presentation- Building a Security Operations Center
SOC presentation- Building a Security Operations CenterSOC presentation- Building a Security Operations Center
SOC presentation- Building a Security Operations Center
 

Semelhante a Perl Development (Sample Courseware)

Introduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable PerlIntroduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable PerlAlex Balhatchet
 
Introduction to Modern Perl
Introduction to Modern PerlIntroduction to Modern Perl
Introduction to Modern PerlDave Cross
 
introductiontoperl-springpeople-150605065831-lva1-app6891.pptx
introductiontoperl-springpeople-150605065831-lva1-app6891.pptxintroductiontoperl-springpeople-150605065831-lva1-app6891.pptx
introductiontoperl-springpeople-150605065831-lva1-app6891.pptxmayilcebrayilov15
 
Introduction To Perl - SpringPeople
Introduction To Perl - SpringPeopleIntroduction To Perl - SpringPeople
Introduction To Perl - SpringPeopleSpringPeople
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
 
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Alex Balhatchet
 
Keeping up with Perl: Development, Upgrade and Deployment Options for Perl 5.12
Keeping up with Perl: Development, Upgrade and Deployment Options for Perl 5.12Keeping up with Perl: Development, Upgrade and Deployment Options for Perl 5.12
Keeping up with Perl: Development, Upgrade and Deployment Options for Perl 5.12ActiveState
 
In-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLIn-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLeSparkBiz
 

Semelhante a Perl Development (Sample Courseware) (20)

Perl Reference.ppt
Perl Reference.pptPerl Reference.ppt
Perl Reference.ppt
 
Introduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable PerlIntroduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable Perl
 
Perl_Part1
Perl_Part1Perl_Part1
Perl_Part1
 
Pearl
PearlPearl
Pearl
 
perl lauange
perl lauangeperl lauange
perl lauange
 
Introduction to Modern Perl
Introduction to Modern PerlIntroduction to Modern Perl
Introduction to Modern Perl
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
introductiontoperl-springpeople-150605065831-lva1-app6891.pptx
introductiontoperl-springpeople-150605065831-lva1-app6891.pptxintroductiontoperl-springpeople-150605065831-lva1-app6891.pptx
introductiontoperl-springpeople-150605065831-lva1-app6891.pptx
 
Introduction To Perl - SpringPeople
Introduction To Perl - SpringPeopleIntroduction To Perl - SpringPeople
Introduction To Perl - SpringPeople
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
 
Perl_Part5
Perl_Part5Perl_Part5
Perl_Part5
 
topic_perlcgi
topic_perlcgitopic_perlcgi
topic_perlcgi
 
topic_perlcgi
topic_perlcgitopic_perlcgi
topic_perlcgi
 
Keeping up with Perl: Development, Upgrade and Deployment Options for Perl 5.12
Keeping up with Perl: Development, Upgrade and Deployment Options for Perl 5.12Keeping up with Perl: Development, Upgrade and Deployment Options for Perl 5.12
Keeping up with Perl: Development, Upgrade and Deployment Options for Perl 5.12
 
Perl programming tsp
Perl  programming tspPerl  programming tsp
Perl programming tsp
 
Perl
PerlPerl
Perl
 
python and perl
python and perlpython and perl
python and perl
 
In-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLIn-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTML
 

Mais de Garth Gilmour

Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android UpdateGarth Gilmour
 
TypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSTypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSGarth Gilmour
 
Shut Up And Eat Your Veg
Shut Up And Eat Your VegShut Up And Eat Your Veg
Shut Up And Eat Your VegGarth Gilmour
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerGarth Gilmour
 
A TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresA TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresGarth Gilmour
 
The Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITThe Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITGarth Gilmour
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerGarth Gilmour
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Garth Gilmour
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in SpaceGarth Gilmour
 
Is Software Engineering A Profession?
Is Software Engineering A Profession?Is Software Engineering A Profession?
Is Software Engineering A Profession?Garth Gilmour
 
Social Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlySocial Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlyGarth Gilmour
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinGarth Gilmour
 
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Garth Gilmour
 
The Three Horse Race
The Three Horse RaceThe Three Horse Race
The Three Horse RaceGarth Gilmour
 
The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming Garth Gilmour
 
BelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopBelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopGarth Gilmour
 
Kotlin The Whole Damn Family
Kotlin The Whole Damn FamilyKotlin The Whole Damn Family
Kotlin The Whole Damn FamilyGarth Gilmour
 

Mais de Garth Gilmour (20)

Compose in Theory
Compose in TheoryCompose in Theory
Compose in Theory
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
TypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSTypeScript Vs. KotlinJS
TypeScript Vs. KotlinJS
 
Shut Up And Eat Your Veg
Shut Up And Eat Your VegShut Up And Eat Your Veg
Shut Up And Eat Your Veg
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
A TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresA TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS Adventures
 
The Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITThe Heat Death Of Enterprise IT
The Heat Death Of Enterprise IT
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
 
Is Software Engineering A Profession?
Is Software Engineering A Profession?Is Software Engineering A Profession?
Is Software Engineering A Profession?
 
Social Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlySocial Distancing is not Behaving Distantly
Social Distancing is not Behaving Distantly
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into Kotlin
 
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
 
The Three Horse Race
The Three Horse RaceThe Three Horse Race
The Three Horse Race
 
The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming
 
BelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopBelTech 2019 Presenters Workshop
BelTech 2019 Presenters Workshop
 
Kotlin The Whole Damn Family
Kotlin The Whole Damn FamilyKotlin The Whole Damn Family
Kotlin The Whole Damn Family
 

Último

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 

Último (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Perl Development (Sample Courseware)

  • 1. Perl Development Sample Courseware Created October 2008 © Garth Gilmour 2008
  • 2.
  • 3. Introduction to Perl History and Basic Concepts © Garth Gilmour 2008
  • 4.
  • 5.
  • 6. Comparing Perl, Python and Ruby © Garth Gilmour 2008 Perl Python Ruby Documentation ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Library Support ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ OO Support ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Power ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Approachability ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Ease of Mastery ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ C / C++ Interop ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Java / .NET Interop ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Web Frameworks ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦
  • 7.
  • 8. © Garth Gilmour 2008 Scripts Core language features Programs Strict module Subroutines References Applications Best Practises Named Parameters Modules and classes
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14. © Garth Gilmour 2008 Symbol Table Typeglob $fred = 12; @fred = (12,13,14); %fred = (k1 =>12, k2 => 14); sub fred { return 101; } Name Link fred Others… Type Link $ @ % &
  • 15.
  • 16. Using Heredoc Comments © Garth Gilmour 2008 $myvar = << &quot;THE_END&quot;; More than prince of cats, I can tell you. O, he is the courageous captain of compliments. He fights as you sing prick-song, keeps time, distance, and proportion; rests me his minim rest, one, two, and the third in your bosom: the very butcher of a silk button, a duellist, a duellist; a gentleman of the very first house, of the first and second cause: ah, the immortal passado! the punto reverso! the hay! THE_END print &quot;--- START DATA ---&quot;, $myvar, &quot;--- END DATA ---&quot;;
  • 17.
  • 18.
  • 19. Basic Programming The Core Perl Syntax © Garth Gilmour 2008
  • 20.
  • 21.
  • 22. Operators Commonly Used in Perl © Garth Gilmour 2008 Description Number Version String Version Addition $var1 + $var2 $var1 . $var2 Equality $var1 == $var2 $var1 eq $va2 Ordered Comparison >, <, <=, >= lt, gt, le, ge Power Of $var1 ** 3 $var1 x 3 Bitwise Comparison &, |, ^ (NB work differently for numbers and strings) Logical &&, ||, ! and, or, not (Lower precedence) Conditional $var1 = $var2 ? 12 : 14; Range 1..4 ‘ D’ .. ‘Z’
  • 23. © Garth Gilmour 2008 $num1 = 42; $num2 = &quot;42&quot;; $result = $num1 + $num2; print &quot;adding numbers gives $result&quot;, &quot;&quot;x2; $result = $num1 . $num2; print &quot;adding strings gives $result&quot;, &quot;&quot;x2; $result = $num2 ** 3; print &quot;42 to the power of 3 is $result&quot;, &quot;&quot;x2; $result = $num1 x 3; print &quot;42 concatenated with itself three times is $result&quot;, &quot;&quot;x2; if($num1 == $num2) { print '$num1 and $num2 are equal as numbers',&quot;&quot;x2; } if($num1 eq $num2) { print '$num1 and $num2 are equal as strings',&quot;&quot;x2; }
  • 24.
  • 25. © Garth Gilmour 2008 $var1 = &quot;abc&quot;; $var2 = 123; $var3 = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]; print 'Values are $var1, $var2 and $var3 '; print &quot;Values are $var1, $var2 and $var3 &quot;; $path = `set path`; print &quot;Value of path environment variable is: $path&quot;; Values are $var1, $var2 and $var3 Values are abc, 123 and ARRAY(0x225e28) Value of path environment variable is: PATH=c:dk1.5.0_05in;C:erlitein;C:erlin;c:ubyin;C:INDOWSystem32;C:INDOWS;C:INDOWSystem32bem;
  • 26.
  • 27. © Garth Gilmour 2008 $var1 = &quot;0&quot;; # The string &quot;0&quot; counts as false $var2 = &quot;&quot;; # The empty string also counts as false $var3 = &quot;AB&quot;; # Other string values are true $var4 = -12; # Other numerical values are true $var5; # Undefined values are false $var6 = undef(); # Values set to undef are false printTruth('$var1',$var1); printTruth('$var2',$var2); printTruth('$var3',$var3); printTruth('$var4',$var4); printTruth('$var5',$var5); printTruth('$var6',$var6); undef($var4); # Release storage space for var1 so it becomes undefined printTruth('$var4',$var4); sub printTruth { my ($varName,$varValue) = @_; if($varValue) { print &quot;$varName is true&quot;; } else { print &quot;$varName is false&quot;; } }
  • 28.
  • 29. Special Scalar Variables © Garth Gilmour 2008 print &quot;This is verson $] of Perl&quot;; print &quot;Running on the $^O operating system&quot;; print &quot;The current script is $0 &quot;; @myarray = (&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;,&quot;gh&quot;); print &quot;Elements are:&quot;; foreach(@myarray) { print &quot; $_ &quot;; } This is verson 5.008008 of Perl Running on the MSWin32 operating system The current script is C:erlpecialScalars.pl Elements are: ab cd ef gh
  • 30.
  • 31. © Garth Gilmour 2008 open(INPUT,&quot;MuchAdoAboutNothing.txt&quot;); $count = 1; foreach(<INPUT>) { print(&quot;$count: $_&quot;); $count++; } 1: Much Ado About Nothing 2: A comedy by William Shakespear 3: 4: Act 1, Scene 1 5: Before LEONATO'S house. 6: Enter LEONATO, HERO, and BEATRICE, with a Messenger 7: 8: LEONATO 9: I learn in this letter that Don Peter of Arragon 10: comes this night to Messina.
  • 32.
  • 33. © Garth Gilmour 2008 print &quot;Enter a number&quot;; $number = <STDIN>; chomp($number); if($number < 10) { print &quot;$number is less than 10&quot;; } elsif($number < 20) { print &quot;$number is less than 20&quot;; } elsif($number < 30) { print &quot;$number is less than 30&quot;; } else { print &quot;$number is greater than 30&quot;; } unless($number % 2 == 0) { print &quot;$number is odd&quot;; } Enter a number 17 17 is less than 20 17 is odd
  • 34.
  • 35. © Garth Gilmour 2008 print &quot;Enter a positive number&quot;; $max = <STDIN>; chomp($max); if($max <= 0) { die(&quot;Number must be positive!&quot;); } print &quot;Demo of while loop&quot;; print &quot;Numbers from 0 to $max are:&quot;; $count = 0; while($count <= $max) { print &quot;$count&quot;; $count++; } print &quot;Demo of do..while loop&quot;; print &quot;Numbers from 0 to $max are:&quot;; $count = 0; do { print &quot;$count&quot;; $count++; } while($count <= $max); print &quot;Demo of until loop&quot;; print &quot;Numbers from 0 to $max are:&quot;; $count = 0; until($count > $max) { print &quot;$count&quot;; $count++; } print &quot;Demo of do..until loop&quot;; print &quot;Numbers from 0 to $max are:&quot;; $count = 0; do { print &quot;$count&quot;; $count++; }until($count > $max); print &quot;Demo of for loop v1&quot;; print &quot;Numbers from 0 to $max are:&quot;; for($count=0; $count<= $max; $count++) { print &quot;$count&quot;; } print &quot;Demo of for each loop v3&quot;; print &quot;Numbers from 0 to $max are:&quot;; for(0..$max) { print &quot;$_&quot;; }
  • 36.
  • 37. Basic Perl I/O Using the Console and Files © Garth Gilmour 2008
  • 38.
  • 39.
  • 40.
  • 41.
  • 42. © Garth Gilmour 2008 open(INPUT,&quot;input.txt&quot;); open(OUTPUT,&quot;>output.txt&quot;); $count = 0; while($line = <INPUT>) { print OUTPUT ++$count, &quot;&quot;, $line; } print &quot;Processed $count lines&quot; This short interval was sufficient to determine d'Artagnan on the part he was to take. It was one of those events which decide the life of a man; it was a choice between the king and the cardinal--the choice made, it must be persisted in. To fight, that was to disobey the law, that was to risk his head, that was to make at one blow an enemy of a minister more powerful than the king himself. All this young man perceived, and yet, to his praise we speak it, he did not hesitate a second. Turning towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to correct your words, if you please. You said you were but three, but it appears to me we are four.&quot; 1 This short interval was sufficient to determine d'Artagnan on the 2 part he was to take. It was one of those events which decide the 3 life of a man; it was a choice between the king and the 4 cardinal--the choice made, it must be persisted in. To fight, 5 that was to disobey the law, that was to risk his head, that was 6 to make at one blow an enemy of a minister more powerful than the 7 king himself. All this young man perceived, and yet, to his 8 praise we speak it, he did not hesitate a second. Turning 9 towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to 10 correct your words, if you please. You said you were but three, 11 but it appears to me we are four.&quot;
  • 43. © Garth Gilmour 2008 open(INPUT, '<', &quot;input.txt&quot;); open(OUTPUT, '>', &quot;output.txt&quot;); $count = 0; while($line = <INPUT>) { print OUTPUT ++$count, &quot;&quot;, $line; } print &quot;Processed $count lines&quot; This short interval was sufficient to determine d'Artagnan on the part he was to take. It was one of those events which decide the life of a man; it was a choice between the king and the cardinal--the choice made, it must be persisted in. To fight, that was to disobey the law, that was to risk his head, that was to make at one blow an enemy of a minister more powerful than the king himself. All this young man perceived, and yet, to his praise we speak it, he did not hesitate a second. Turning towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to correct your words, if you please. You said you were but three, but it appears to me we are four.&quot; 1 This short interval was sufficient to determine d'Artagnan on the 2 part he was to take. It was one of those events which decide the 3 life of a man; it was a choice between the king and the 4 cardinal--the choice made, it must be persisted in. To fight, 5 that was to disobey the law, that was to risk his head, that was 6 to make at one blow an enemy of a minister more powerful than the 7 king himself. All this young man perceived, and yet, to his 8 praise we speak it, he did not hesitate a second. Turning 9 towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to 10 correct your words, if you please. You said you were but three, 11 but it appears to me we are four.&quot;
  • 44. © Garth Gilmour 2008 open($input, '<', &quot;input.txt&quot;); open($output, '>', &quot;output.txt&quot;); $count = 0; while($line = <$input>) { print $output ++$count, &quot;&quot;, $line; } print &quot;Processed $count lines&quot; This short interval was sufficient to determine d'Artagnan on the part he was to take. It was one of those events which decide the life of a man; it was a choice between the king and the cardinal--the choice made, it must be persisted in. To fight, that was to disobey the law, that was to risk his head, that was to make at one blow an enemy of a minister more powerful than the king himself. All this young man perceived, and yet, to his praise we speak it, he did not hesitate a second. Turning towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to correct your words, if you please. You said you were but three, but it appears to me we are four.&quot; 1 This short interval was sufficient to determine d'Artagnan on the 2 part he was to take. It was one of those events which decide the 3 life of a man; it was a choice between the king and the 4 cardinal--the choice made, it must be persisted in. To fight, 5 that was to disobey the law, that was to risk his head, that was 6 to make at one blow an enemy of a minister more powerful than the 7 king himself. All this young man perceived, and yet, to his 8 praise we speak it, he did not hesitate a second. Turning 9 towards Athos and his friends, &quot;Gentlemen,&quot; said he, &quot;allow me to 10 correct your words, if you please. You said you were but three, 11 but it appears to me we are four.&quot;
  • 45.
  • 46. © Garth Gilmour 2008 open($input, '<', &quot;input.txt&quot;) or die &quot;Can't open input&quot;; open($output, '>', &quot;output.txt&quot;) or die &quot;Can't open output&quot;; $count = 0; while($line = <$input>) { print($output ++$count, &quot;&quot;, $line) or die &quot;Can't write to file&quot;; } print &quot;Processed $count lines&quot;; close($input) or die &quot;Can't close input&quot;; close($output) or die &quot;Can't close output&quot;;
  • 47.
  • 48. © Garth Gilmour 2008 @exampleDirectories = glob('..'); print &quot;Perl example files are: &quot;; foreach $dir (@exampleDirectories) { @perlFiles = glob($dir . '.pl'); foreach(@perlFiles) { #characters preceding a slash preceding # letters ending in '.pl' m/.*(+pl)/; print &quot;$1 in $dir &quot;; } } Perl example files are: arrayFunctions.pl in ..rrays arraysAndLists.pl in ..rrays days.pl in ..rrays forEach.pl in ..rrays fork.pl in ..oncurrency threads.pl in ..oncurrency customerDB.pl in ..atabases arraysOfArrays.pl in ..ataStructures checkingErrors.pl in ..iles indirectHandles.pl in ..iles basicHashes.pl in ..ashes extraSyntax.pl in ..ashes
  • 49. Arrays in Perl Creating and Using Lists © Garth Gilmour 2008
  • 50.
  • 51. © Garth Gilmour 2008 $myarray[8] = &quot;string in 9th box&quot;; $myarray[10] = &quot;string in 11th box&quot;; $count = 0; foreach(@myarray) { print $count++,&quot;: $_&quot;; } 0: 1: 2: 3: 4: 5: 6: 7: 8: string in 9th box 9: 10: string in 11th box
  • 52.
  • 53.
  • 54. © Garth Gilmour 2008 @tstArray = qw(abc def ghi jkl mno pqr); ($first) = @tstArray; ($a,$b,$c) = @tstArray; print &quot;First element is: $first&quot;; print &quot;First three elements are: $a $b $c&quot; First element is: abc First three elements are: abc def ghi
  • 55.
  • 56.
  • 57. © Garth Gilmour 2008 @workDays = (&quot;Monday&quot;,&quot;Tuesday&quot;,&quot;Wednesday&quot;,&quot;Thursday&quot;,&quot;Friday&quot;); @weekendDays = qw(Saturday Sunday); @days = (@workDays,@weekendDays); $numDays = @days; $firstDay = $days[0]; $lastDay = $days[$#days]; print &quot;There are $numDays days in a week&quot;; print &quot;$firstDay is the first day and $lastDay is the last day &quot;; print &quot;The other days are:&quot;; foreach $day (@days) { unless($day eq $firstDay or $day eq $lastDay) { print $day, &quot;&quot;; } } print &quot;The last four days are:&quot;; @lastDays = @days[3..6]; foreach $day (@lastDays) { print $day, &quot;&quot;; }
  • 58.
  • 59.
  • 60. © Garth Gilmour 2008 @myarray1 = qw(abc def ghi); $val1 = pop(@myarray1); print &quot;Just popped $val1, contents now:&quot;; foreach(@myarray1) { print &quot;$_&quot;; } push(@myarray1,&quot;zzz&quot;); print &quot;Just pushed zzz, contents now:&quot;; foreach(@myarray1) { print &quot;$_&quot;; } $val1 = shift(@myarray1); print &quot;Just shifted $val1, contents now:&quot;; foreach(@myarray1) { print &quot;$_&quot;; } unshift(@myarray1,&quot;AAA&quot;); print &quot;Just unshifted AAA, contents now:&quot;; foreach(@myarray1) { print &quot;$_&quot;; } Just popped ghi, contents now: abc def Just pushed zzz, contents now: abc def zzz Just shifted abc, contents now: def zzz Just unshifted AAA, contents now: AAA def zzz
  • 61. Hashes in Perl Creating and Using Tables © Garth Gilmour 2008
  • 62.
  • 63. © Garth Gilmour 2008 $myhash{'k1'} = &quot;abc&quot;; $myhash{'k2'} = 123; $myhash{'k3'} = &quot;def&quot;; $myhash{'k4'} = 456; foreach $key (keys %myhash) { print $key, &quot; indexes &quot;, $myhash{$key}, &quot;&quot;; } k2 indexes 123 k1 indexes abc k3 indexes def k4 indexes 456
  • 64.
  • 65.
  • 66.
  • 67. © Garth Gilmour 2008 %myhash = ( k1 => 123, k2 => &quot;abc&quot;, k3 => 456, k4 => &quot;def&quot;, k5 => 789 ); print &quot;Keys are:&quot;; foreach $key (keys %myhash) { print &quot;&quot;, $key, &quot;&quot;; } print &quot;Values are:&quot;; foreach $value (values %myhash) { print &quot;&quot;, $value, &quot;&quot;; } print &quot;Entries are:&quot;; while (($key, $value) = each(%myhash)) { print &quot;$key indexes $value &quot;; } Keys are: k5 k2 k1 k3 k4 Values are: 789 abc 123 456 def Entries are: k5 indexes 789 k2 indexes abc k1 indexes 123 k3 indexes 456 k4 indexes def
  • 68.
  • 69. © Garth Gilmour 2008 %tstHash = (&quot;k1&quot;,&quot;v1&quot;,&quot;k2&quot;,&quot;v2&quot;); print &quot;Original hash contents:&quot;; foreach(keys(%tstHash)) { print(&quot;$_ indexes &quot;,$tstHash{$_},&quot;&quot;); } @tstHash {&quot;k3&quot;,&quot;k4&quot;,&quot;k5&quot;,&quot;k6&quot;} = (111,222,333,444); print &quot;Hash contents after insertions:&quot;; foreach(keys(%tstHash)) { print(&quot;$_ indexes &quot;,$tstHash{$_},&quot;&quot;); } ($var1,$var2,$var3) = @tstHash {&quot;k1&quot;,&quot;k2&quot;,&quot;k3&quot;}; print &quot;Values in scalars are $var1 $var2 and $var3&quot;; @elements = %tstHash; print &quot;Array contents:&quot;; foreach(@elements) { print &quot;$_ &quot;; } Original hash contents: k2 indexes v2 k1 indexes v1 Hash contents after insertions: k5 indexes 333 k2 indexes v2 k1 indexes v1 k6 indexes 444 k3 indexes 111 k4 indexes 222 Values in scalars are v1 v2 and 111 Array contents: k5 333 k2 v2 k1 v1 k6 444 k3 111 k4 222
  • 70.
  • 71. © Garth Gilmour 2008 %results = ( dave => [54, 62, 73, 48], jane => [59, 67, 82, 70], fred => [92, 64, 59, 71] ); results dave jane fred 54 62 73 48 59 67 82 70 92 64 59 71
  • 72.
  • 73. © Garth Gilmour 2008 %actors = ( &quot;george clooney&quot; => [&quot;Oceans 11&quot;, &quot;The Peacemaker&quot;, &quot;O Brother Where Art Thou&quot;], &quot;harrison ford&quot; => [&quot;Star Wars&quot;,&quot;Sabrina&quot;,&quot;Indiana Jones&quot;], &quot;robin williams&quot; => [&quot;Good Morning Vietnam&quot;,&quot;Hook&quot;,&quot;The Birdcage&quot;] ); print &quot;The list of actors and their movies is: &quot;; foreach $actor (keys %actors) { print &quot;$actor starred in: &quot;; foreach $film(@{$actors{$actor}}) { print &quot;$film&quot;; } } The list of actors and their movies is: robin williams starred in: Good Morning Vietnam Hook The Birdcage harrison ford starred in: Star Wars Sabrina Indiana Jones george clooney starred in: Oceans 11 The Peacemaker O Brother Where Art Thou
  • 74. Regular Expressions Part 1: Core Concepts © Garth Gilmour 2008
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84. © Garth Gilmour 2008 ABCdefGHIjklMNOpqrSTU [A-Z]{2} Matches: AB GH MN ST ABCdefGHIjklMNOpqrSTU [A-Z]{3} Matches: ABC GHI MNO STU ABCdefGHIjklMNOpqrSTU [A-Z]{3}[a-z] Matches: ABCd GHIj MNOp
  • 85. © Garth Gilmour 2008 ABCdefGHIjklMNOpqrSTU [A-Z]+[a-z]+ Matches: ABCdef GHIjkl MNOpqr ABCdefGHIjklMNOpqrSTU ([A-Z]+)([a-z]+) Matches: ABCdef Group 1: ABC Group 2: def GHIjkl Group 1: GHI Group 2: jkl MNOpqr Group 1: MNO Group 2: pqr ABCdefGHIjklMNOpqrSTU [A-Za-z]+ Matches: ABCdefGHIjklMNOpqrSTU
  • 86. © Garth Gilmour 2008 ABCdefGHIjklMNOpqrSTU [A-Za-z]{5} Matches: ABCde fGHIj klMNO pqrST ABCdefGHIjklMNOpqrSTU ^[A-Za-z]{5} Matches: ABCde ABCdefGHIjklMNOpqrSTU [A-Za-z]{5}$ Matches: qrSTU ABCdefGHIjklMNOpqrSTU [A-Za-z]{5,8} Matches: ABCdefGH IjklMNOp rqSTU
  • 87.
  • 88. Regular Expressions Part 2: Perl Syntax © Garth Gilmour 2008
  • 89.
  • 90. © Garth Gilmour 2008 $data = &quot;ABCdefGHIjklMNOpqrSTUvwxYZA&quot;; $m1 = $data =~ m/[A-Z]/; if($m1) { print &quot;Match one is $&&quot;; } $m2 = $data =~ m/[A-Z]{2}/; if($m2) { print &quot;Match two is $&&quot;; } $m3 = $data =~ m/[A-Z]+/; if($m3) { print &quot;Match three is $&&quot;; } $m4 = $data =~ m/[^e]+/; if($m4) { print &quot;Match four is $&&quot;; } $m5 = $data =~ m/[A-Z]{3}[a-z]{2}/; if($m5) { print &quot;Match five is $&&quot;; } Match one is A Match two is AB Match three is ABC Match four is ABCd Match five is ABCde
  • 91. © Garth Gilmour 2008 $m6 = $data =~ m/[A-Z]+[a-z]+/; if($m6) { print &quot;Match six is $&&quot;; } $m7 = $data =~ m/[A-Za-z]{9}/; if($m7) { print &quot;Match seven is $&&quot;; } $m8 = $data =~ m/.+/; if($m8) { print &quot;Match eight is $&&quot;; } $m9 = $data =~ m/^.{8}/; if($m9) { print &quot;Match nine is $&&quot;; } $m10 = $data =~ m/.{8}$/; if($m10) { print &quot;Match ten is $&&quot;; } Match six is ABCdef Match seven is ABCdefGHI Match eight is ABCdefGHIjklMNOpqrSTUvwxYZA Match nine is ABCdefGH Match ten is TUvwxYZA
  • 92. © Garth Gilmour 2008 @groupOne = $data =~ m/[A-Z]{3}/g; print &quot;First group of matches are:&quot;; foreach(@groupOne) { print &quot;$_&quot;; } @groupTwo = $data =~ m/[a-z]{3}/g; print &quot;Second group of matches are:&quot;; foreach(@groupTwo) { print &quot;$_&quot;; } @groupThree = $data =~ m/.{4}/g; print &quot;Third group of matches are:&quot;; foreach(@groupThree) { print &quot;$_&quot;; } First group of matches are: ABC GHI MNO STU YZA Second group of matches are: def jkl pqr vwx Third group of matches are: ABCd efGH Ijkl MNOp qrST Uvwx
  • 93.
  • 94.
  • 95. Using Regular Expressions in Perl © Garth Gilmour 2008 print &quot;Enter the email address:&quot;; chomp($email = <STDIN>); #easier to read version of ([a-z]+([a-z]+)?)megacorp(com|ie|couk) $m = $email =~ m{^ #start of string ( #start of inner match 1 [a-z]+ #one or more lowercase letters ([a-z]+)? #optionally a dot and letters (inner match 2) ) #end of inner match 1 megacorp #company name NB need to escape array (com|ie|couk) #possible domain names $ #end of string }x; if($m) { print &quot;Recognized email for $1 in domain $3&quot;; } else { print &quot;Invalid address!&quot;; }
  • 96.
  • 97. © Garth Gilmour 2008 $test = &quot;aabbccddyzeeffgghhiijjkkllmmnnoo&quot;; # Replace all occurances of ff with FF $test =~ s/ff/FF/g; print $test , &quot;&quot;; # Replace any occurance of four characters at the start of the string with XX $test =~ s/^.{4}/XX/g; print $test , &quot;&quot;; # Replace any lower case characters with their upper case equivalents $test =~ s/([a-z])/uc($1)/eg; print $test , &quot;&quot;; aabbccddyzeeFFgghhiijjkkllmmnnoo XXccddyzeeFFgghhiijjkkllmmnnoo XXCCDDYZEEFFGGHHIIJJKKLLMMNNOO
  • 98. Regular Expressions Part 3: Advanced Concepts © Garth Gilmour 2008
  • 99.
  • 100.
  • 101. © Garth Gilmour 2008 abcDEfghIJklm [a-zA-Z]+[A-Z]{2} abcDEfghIJ Matches: abcDE fghIJ [a-zA-Z]+?[A-Z]{2} [a-zA-Z]*[A-Z]{2} abcDEfghIJklm Matches: ab cDEfg hIJkl [a-zA-Z]*?[A-Z]{2}
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108. Sample Unicode Properties © Garth Gilmour 2008 Unicode Property Description AHex True for ASCII characters used in hexadecimal numbers Alpha True if a character can be compared to others ea The East Asian width of a character (full, half or narrow) IDC Indicates if a character can only be used as the first in an identifier Math True if the character is used in describing mathematical expressions Lower Indicates if a character is a lowercase letter STerm Indicates if a character is used to terminate a sentence Term Indicates if a character is punctuation that terminates a unit WSpace Indicates if a character should be treated as whitespace during parsing
  • 109.
  • 110. Perl Subroutines Creating and Calling Functions © Garth Gilmour 2008
  • 111.
  • 112. © Garth Gilmour 2008 sub func { my($param1, $param2, $param3, $param4, $param5) = @_; print &quot;func called with:&quot;; print &quot;$param1&quot;; print &quot;$param2&quot;; print &quot;$param3&quot;; print &quot;$param4&quot;; print &quot;$param5&quot;; } func(&quot;abc&quot;,123,&quot;def&quot;,456,&quot;ghi&quot;); func called with: abc 123 def 456 ghi
  • 113.
  • 114.
  • 115. © Garth Gilmour 2008 $var1 = &quot;ABC&quot;; $var2 = &quot;DEF&quot;; $var3 = &quot;GHI&quot;; print &quot;At start $var1, $var2 and $var3&quot;; func1(); print &quot;At end $var1, $var2 and $var3&quot;; sub func1 { my $var1 = &quot;JKL&quot;; local $var2 = &quot;MNO&quot;; our $var3; print &quot;In func1 $var1, $var2 and $var3&quot;; func2(); } sub func2 { print &quot;In func2 $var1, $var2 and $var3&quot;; } At start ABC, DEF and GHI In func1 JKL, MNO and GHI In func2 ABC, MNO and GHI At end ABC, DEF and GHI
  • 116.
  • 117. © Garth Gilmour 2008 sub func { my %params = @_; print &quot;Parameter fred has value $params{'fred'}&quot;; print &quot;Parameter wilma has value $params{'wilma'}&quot;; print &quot;Parameter barney has value $params{'barney'}&quot;; } print &quot;---------- First Call ----------&quot;; @args1 = (&quot;fred&quot;,20,&quot;wilma&quot;,30,&quot;barney&quot;,40); func(@args1); print &quot;---------- Second Call ----------&quot;; @args2 = (fred => 50, wilma => 60, barney => 70); func(@args2); print &quot;---------- Third Call ----------&quot;; func(fred => 80, wilma => 90, barney => 100); ---------- First Call ---------- Parameter fred has value 20 Parameter wilma has value 30 Parameter barney has value 40 ---------- Second Call ---------- Parameter fred has value 50 Parameter wilma has value 60 Parameter barney has value 70 ---------- Third Call ---------- Parameter fred has value 80 Parameter wilma has value 90 Parameter barney has value 100
  • 118.
  • 119. Subroutines and Recursion © Garth Gilmour 2008 sub recursion1 { until($_[0] == 0) { print &quot;$_[0] &quot;; $_[0]--; &recursion1; } } sub recursion2 { if(@_) { print(shift, &quot; &quot;); &recursion2; } } $val1 = 10; recursion1($val1); print &quot;&quot;; @val2 = qw(abc def ghi jkl); recursion2(@val2); 10 9 8 7 6 5 4 3 2 1 abc def ghi jkl
  • 120.
  • 121. © Garth Gilmour 2008 Closures are cool! Closures are cool! Closures are cool! Closures are cool! Closures are cool! Closures are very cool! Closures are very cool! Closures are very cool! ab cd ef gh sub doTimes { for(1..$_[0]) { &{$_[1]}(); } } sub withMatches { for($_[0] =~ m/$_[1]/g) { &{$_[2]}($_); } } $ref = sub { print &quot;Closures are cool!&quot;; }; doTimes(5, $ref); doTimes(3, sub { print &quot;Closures are very cool!&quot;; }); withMatches(&quot;ab cd ef gh&quot;, &quot;[a-z]{2}&quot;, sub { print &quot;$_[0]&quot;; });
  • 122. Error Handling Managing Error Conditions © Garth Gilmour 2008
  • 123.
  • 124. © Garth Gilmour 2008 eval { op1(); }; if($@) { print &quot;Code threw error: &quot;, $@; } sub op1 { op2(); } sub op2 { op3(); } sub op3 { die &quot;BOOM!&quot;; } eval { op1(); }; if($@) { print &quot;Error of severity &quot;, $@->{'severity'}; print &quot; thrown with message &quot;, $@->{'msg'}; } sub op1 { op2(); } sub op2 { op3(); } sub op3 { my %error = (msg => 'BOOM!', severity => 'fatal'); die error; }
  • 125. References in Perl Using Memory Addresses © Garth Gilmour 2008
  • 126.
  • 127. © Garth Gilmour 2008 $var1 = 124; $ref1 = var1; print $ref1, &quot;&quot;; print &quot;Reference ref1 refers to value $$ref1&quot;; print &quot;Reference ref1 refers to value ${$ref1}&quot;; SCALAR(0x226d98) Reference ref1 refers to value 124 Reference ref1 refers to value 124
  • 128. © Garth Gilmour 2008 @var2 = (&quot;abc&quot;,&quot;def&quot;,&quot;ghi&quot;,&quot;jkl&quot;); $ref2 = var2; print $ref2, “”; print &quot;Reference ref2 refers to array with contents: &quot;; foreach $val (@$ref2) { print &quot;$val &quot;; } print &quot;Reference ref2 refers to array with contents: &quot;; foreach $val (@{$ref2}) { print &quot;$val &quot;; } print &quot;First three elements in array pointed to by ref2 are: &quot;; @slice = @{$ref2}[0..2]; foreach $val (@slice) { print &quot;$val &quot;; } print &quot;First item is $$ref2[0]&quot;; print &quot;First item is ${$ref2}[0]&quot;; print &quot;First item is $ref2->[0]&quot;;
  • 129. © Garth Gilmour 2008 ARRAY(0x226da4) Reference ref2 refers to array with contents: abc def ghi jkl Reference ref2 refers to array with contents: abc def ghi jkl First three elements in array pointed to by ref2 are: abc def ghi First item is abc First item is abc First item is abc
  • 130. © Garth Gilmour 2008 %var3 = (&quot;k1&quot;,&quot;xxx&quot;,&quot;k2&quot;,&quot;yyy&quot;,&quot;k3&quot;,&quot;zzz&quot;); $ref3 = var3; print &quot;Reference ref3 refers to hash with contents:&quot;; foreach $key (keys %$ref3) { print &quot;$key indexes $$ref3{$key}&quot;; } print &quot;Reference ref3 refers to hash with contents:&quot;; foreach $key (keys %{$ref3}) { print &quot;$key indexes $ref3->{$key}&quot;; } print &quot;Key k1 indexes $$ref3{'k1'} &quot;; print &quot;Key k1 indexes ${$ref3}{'k1'} &quot;; print &quot;Key k1 indexes $ref3->{'k1'} &quot;;
  • 131. © Garth Gilmour 2008 Reference ref3 refers to hash with contents: k2 indexes yyy k1 indexes xxx k3 indexes zzz Reference ref3 refers to hash with contents: k2 indexes yyy k1 indexes xxx k3 indexes zzz Key k1 indexes xxx Key k1 indexes xxx Key k1 indexes xxx
  • 132.
  • 133. © Garth Gilmour 2008 $ref1 = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;,&quot;gh&quot;]; $ref2 = { k1 => 123, k2 => 456, k3 => 789 }; $ref3 = sub { return $_[0] + $_[1]; }; print $ref1, &quot;&quot;; print $ref2, &quot;&quot;; print $ref3, &quot;&quot;; print $ref1->[0], &quot;&quot;; print $ref2->{'k1'}, &quot;&quot;; print $ref3->(12,5), &quot;&quot;; ARRAY(0x225f88) HASH(0x226d80) CODE(0x18303f0) ab 123 17
  • 134.
  • 135. © Garth Gilmour 2008 @numerals = ( [100,&quot;C&quot;], [90,&quot;XC&quot;], [50,&quot;L&quot;], [40,&quot;XL&quot;], [10,&quot;X&quot;], [9,&quot;IX&quot;], [5,&quot;V&quot;], [4,&quot;IV&quot;], [1,&quot;I&quot;] ); print &quot;Enter the number to convert to a roman numeral...&quot;; $number = <STDIN>; chomp($number); foreach (@numerals) { my $decimal = $_->[0]; my $string = $_->[1]; my $times = int($number / $decimal); if($times > 0) { for(1..$times) { print $string; } $number = $number % $decimal; } }
  • 136. © Garth Gilmour 2008 $ref1 = [ [&quot;abc&quot;,&quot;def&quot;,&quot;ghi&quot;], [&quot;jkl&quot;,&quot;mno&quot;,&quot;pqr&quot;], [&quot;stu&quot;,&quot;vwx&quot;,&quot;yza&quot;] ]; print &quot;Contents of 2d array are:&quot;; foreach(@{$ref1}) { print &quot;&quot;; foreach(@{$_}) { print &quot;$_ &quot;; } print &quot;&quot;; } Contents of 2d array are: abc def ghi jkl mno pqr stu vwx yza
  • 137. © Garth Gilmour 2008 $ref = { k1 => { k4 => &quot;ab&quot;, k5 => &quot;cd&quot; }, k2 => { k6 => &quot;ef&quot;, k7 => &quot;gh&quot; }, k3 => { k8 => &quot;ij&quot;, k9 => &quot;kl&quot; } }; print $ref->{'k1'}->{'k4'}, &quot;&quot;; print $ref->{'k1'}->{'k5'}, &quot;&quot;; print $ref->{'k2'}->{'k6'}, &quot;&quot;; print $ref->{'k2'}->{'k7'}, &quot;&quot;; print $ref->{'k3'}->{'k8'}, &quot;&quot;; print $ref->{'k3'}->{'k9'}, &quot;&quot;; ab cd ef gh ij kl
  • 138. Modules and Packages Creating Reusable Code © Garth Gilmour 2008
  • 139.
  • 140.
  • 141.
  • 142. © Garth Gilmour 2008 package Maths; require Exporter; our @ISA = (&quot;Exporter&quot;); @EXPORT = qw(add multiply subtract); sub add { return $_[0] + $_[1]; } sub divide { return $_[0] / $_[1]; } sub multiply { return $_[0] * $_[1]; } sub subtract { return $_[0] - $_[1]; } use Maths; print &quot;Calculations using our maths module:&quot;; print &quot;40 + 30 is: &quot;, add(40,30); print &quot;60 - 20 is: &quot;, subtract(60,20); print &quot;50 * 10 is: &quot;, multiply(50,10); # divide is not exported so it only works # if we qualify the namespace print &quot;40 / 10 is: &quot;, Maths::divide(40,10);
  • 143. © Garth Gilmour 2008 package Maths; require Exporter; our @ISA = (&quot;Exporter&quot;); @EXPORT_OK = qw(add multiply subtract); sub add { return $_[0] + $_[1]; } sub divide { return $_[0] / $_[1]; } sub multiply { return $_[0] * $_[1]; } sub subtract { return $_[0] - $_[1]; } use Maths qw(add multiply subtract); print &quot;Calculations using our maths module:&quot;; print &quot;40 + 30 is: &quot;, add(40,30); print &quot;60 - 20 is: &quot;, subtract(60,20); print &quot;50 * 10 is: &quot;, multiply(50,10); # divide is not exported so it only works # if we qualify the namespace print &quot;40 / 10 is: &quot;, Maths::divide(40,10);
  • 144.
  • 145. Objects in Perl Support for Object Oriented Programming Concepts © Garth Gilmour 2008
  • 146.
  • 147.
  • 148. © Garth Gilmour 2008 Client Code Account Objects account1 account2 withdraw { … } display { … } withdraw { … } display { … }
  • 149. © Garth Gilmour 2008 class Account: def __init__(self,id,balance): self.id = id self.balance = balance def withdraw(self, amount): self.balance -= amount def display(self): print &quot;Account with id&quot;, self.id, &quot;and balance&quot;, self.balance account1 = Account(&quot;AB12&quot;,30000) account2 = Account(&quot;CD34&quot;,45000) print &quot;----- Before Withdrawl -----&quot; account1.display() account2.display() account1.withdraw(250) account2.withdraw(500) print &quot;----- After Withdrawl -----&quot; account1.display() account2.display() ----- Before Withdrawl ----- Account with id AB12 and balance 30000 Account with id CD34 and balance 45000 ----- After Withdrawl ----- Account with id AB12 and balance 29750 Account with id CD34 and balance 44500 Constructor Class Declaration Creating Objects
  • 150. © Garth Gilmour 2008 class Account def initialize(id, balance) @id = id @balance = balance end def withdraw(amount) @balance -= amount end def display() puts &quot;Account with id #{@id} and balance #{@balance}&quot; end end account1 = Account.new(&quot;AB12&quot;,30000) account2 = Account.new(&quot;CD34&quot;,45000) puts &quot;----- Before Withdrawl -----&quot; account1.display() account2.display() account1.withdraw(250) account2.withdraw(500) puts &quot;----- After Withdrawl -----&quot; account1.display() account2.display() ----- Before Withdrawl ----- Account with id AB12 and balance 30000 Account with id CD34 and balance 45000 ----- After Withdrawl ----- Account with id AB12 and balance 29750 Account with id CD34 and balance 44500 Class Declaration Constructor Creating Objects
  • 151.
  • 152. © Garth Gilmour 2008 package Account; sub new { my $packageName = shift; my $data = {}; $data->{'id'} = shift; $data->{'balance'} = shift; bless $data, $packageName; } sub withdraw { my $data = shift; $data->{'balance'} -= $_[0]; } sub display { my $data = shift; print &quot;Account with id $data->{'id'} and balance $data->{'balance'}&quot;; } Packages double as classes Any method can be a constructor Anonymous hashes hold fields
  • 153. © Garth Gilmour 2008 $account1 = Account->new(&quot;AB12&quot;,30000); $account2 = Account->new(&quot;CD34&quot;,45000); print &quot;----- Before Withdrawl -----&quot;; $account1->display(); $account2->display(); $account1->withdraw(250); $account2->withdraw(500); print &quot;----- After Withdrawl -----&quot;; $account1->display(); $account2->display(); ----- Before Withdrawl ----- Account with id AB12 and balance 30000 Account with id CD34 and balance