Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83, , 659, perlsub manpage
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 2 In this topic Command-line arguments The diamond operator <> Subroutines ► declaring ► calling ► returning from Local variables Perl debugger Command-line arguments The diamond operator <> Subroutines ► declaring ► calling ► returning from Local variables Perl debugger
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 3 Command-line arguments Words on command line after script name are considered command-line arguments ► perl -w mystery Agatha Arthur "Erle Stanley" –three command-line arguments: “Agatha”, “Arthur”, “Erle Stanley” –broken up into space-separated words by shell –except where quoted or escaped Command-line arguments are available to Perl array ► first argument is in $ARGV[0] –not like C, where argv[0] is program name –Perl script name can be found in special variable $0 (zero) ► unlike C, no need for argc parameter ’s size is known ► if no command-line is empty Words on command line after script name are considered command-line arguments ► perl -w mystery Agatha Arthur "Erle Stanley" –three command-line arguments: “Agatha”, “Arthur”, “Erle Stanley” –broken up into space-separated words by shell –except where quoted or escaped Command-line arguments are available to Perl array ► first argument is in $ARGV[0] –not like C, where argv[0] is program name –Perl script name can be found in special variable $0 (zero) ► unlike C, no need for argc parameter ’s size is known ► if no command-line is empty Llama3 pages 90-91; Camel3 page 659; perlvar manpage
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 4 Timeout #!/usr/bin/perl -w print "Program name is: $0\n"; print "Parameters are:\n"; for ($i = 0; $i <= $#ARGV; $i++) { print " $i: $ARGV[$i]\n"; } #!/usr/bin/perl -w print "Program name is: $0\n"; print "Parameters are:\n"; for ($i = 0; $i <= $#ARGV; $i++) { print " $i: $ARGV[$i]\n"; }
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 5 Filters Many Unix programs can act as filters ► if files named on command line, program processes files in order –sort file1 file3 file4 # Sort all together ► if no files named on command line, program processes standard input –cat file1 file3 file4 | sort # Same ► filename “ - ” also means standard input –sort filling | cat slice1 - slice2 # Sandwich Perl makes this easy with <> (“diamond”) operator ► <> reads lines of input, like Many Unix programs can act as filters ► if files named on command line, program processes files in order –sort file1 file3 file4 # Sort all together ► if no files named on command line, program processes standard input –cat file1 file3 file4 | sort # Same ► filename “ - ” also means standard input –sort filling | cat slice1 - slice2 # Sandwich Perl makes this easy with <> (“diamond”) operator ► <> reads lines of input, like Llama3 pages 88-90; Camel3 pages 80-83
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 6 <> (diamond) operator If files named as command-line arguments ► <> returns lines from file named in $ARGV[0] ► then returns lines from file named in $ARGV[1] ► until all lines in all files read, then returns undef ► no need to open or close files or detect EOF between files If no command-line arguments ► <> behaves the same as If files named as command-line arguments ► <> returns lines from file named in $ARGV[0] ► then returns lines from file named in $ARGV[1] ► until all lines in all files read, then returns undef ► no need to open or close files or detect EOF between files If no command-line arguments ► <> behaves the same as
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 7 Timeout #!/usr/bin/perl -w # Unix cat program while (<>) { print; } #!/usr/bin/perl -w # Unix cat program while (<>) { print; }
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 8 Timeout #!/usr/bin/perl -w # Even shorter Unix cat program print while (<>); # That’s it. #!/usr/bin/perl -w # Even shorter Unix cat program print while (<>); # That’s it.
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 9 Subroutines In Perl, functions are called subroutines ► declared with sub keyword In Perl, functions are called subroutines ► declared with sub keyword sub name { # Body goes here } sub keyword declares the subroutine put name of subroutine here Llama3 page 57; Camel3 pages ; perlsyn manpage
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 10 Calling subroutines Subroutines officially begin with & character ► $thing is is array, &thing is subroutine In practice, & is almost never needed ► not used when defining with sub keyword ► not needed when calling because parentheses identify it as a subroutine ► &weekday(2004,6,1) or weekday(2004,6,1) Subroutines officially begin with & character ► $thing is is array, &thing is subroutine In practice, & is almost never needed ► not used when defining with sub keyword ► not needed when calling because parentheses identify it as a subroutine ► &weekday(2004,6,1) or weekday(2004,6,1) Llama3 pages57-58, 70-71; Camel3 page 218
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 11 Calling subroutines Caller names arguments as list after subroutine name ► $newyearsday = weekday($year, 1, 1); ► as with built-in functions, can omit parentheses if subroutine is predeclared Argument list is evaluated and placed in special local array ► argument is unrelated to default argument $_ Subroutine can access members to get parameter values ► sub weekday { ($y, $m, $d) } ► sub weekday { $y = $_[0];... } Caller names arguments as list after subroutine name ► $newyearsday = weekday($year, 1, 1); ► as with built-in functions, can omit parentheses if subroutine is predeclared Argument list is evaluated and placed in special local array ► argument is unrelated to default argument $_ Subroutine can access members to get parameter values ► sub weekday { ($y, $m, $d) } ► sub weekday { $y = $_[0];... } Llama3 pages 60-62; Camel3 pages
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 12 Subroutine return Return value of a subroutine is the last expression evaluated ► sub pi { ; } Can use return keyword to return sooner ► sub absx { if ($x >= 0) { return $x; } else { return -$x; } } Return value can be scalar or list ► return (1, 2, 3); ► return value is evaluated in scalar or list context depending on context subroutine was called in ► can use wantarray function to determine context Return value of a subroutine is the last expression evaluated ► sub pi { ; } Can use return keyword to return sooner ► sub absx { if ($x >= 0) { return $x; } else { return -$x; } } Return value can be scalar or list ► return (1, 2, 3); ► return value is evaluated in scalar or list context depending on context subroutine was called in ► can use wantarray function to determine context Llama3 pages 58-60, 69-70; Camel3 pages 219,228
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 13 Timeout # Compute the hypotenuse of a triangle # Declare the subroutine sub hypotenuse { # Return root of sum of squares. sqrt($_[0] * $_[0] + $_[1] * $_[1]); } # Read two numbers. print "Enter first number: "; chomp ($a = ); print "Enter second number: "; chomp ($b = ); print "Hypotenuse is ", hypotenuse($a, $b), "\n"; # Compute the hypotenuse of a triangle # Declare the subroutine sub hypotenuse { # Return root of sum of squares. sqrt($_[0] * $_[0] + $_[1] * $_[1]); } # Read two numbers. print "Enter first number: "; chomp ($a = ); print "Enter second number: "; chomp ($b = ); print "Hypotenuse is ", hypotenuse($a, $b), "\n";
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 14 Timeout # Compute the hypotenuse of a triangle # Declare the subroutine sub hypotenuse { # Give the parameters meaningful names. ($x, $y) # This has a slight bug. sqrt($x * $x + $y * $y); } # Read two numbers. print "Enter first number: "; chomp ($a = ); print "Enter second number: "; chomp ($b = ); print "Hypotenuse is ", hypotenuse($a, $b), "\n"; # Compute the hypotenuse of a triangle # Declare the subroutine sub hypotenuse { # Give the parameters meaningful names. ($x, $y) # This has a slight bug. sqrt($x * $x + $y * $y); } # Read two numbers. print "Enter first number: "; chomp ($a = ); print "Enter second number: "; chomp ($b = ); print "Hypotenuse is ", hypotenuse($a, $b), "\n";
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 15 Local variables with my By default, all variables are global Variables can be declared local with my function ► my $x; Variables declared with my are accessible only within enclosing block (usually until end of loop or subroutine) ► “lexical scoping”, like local variables in C ► Perl also has “dynamic scoping” like shell, uses local function Can localize more than one variable at once ► my ($x, # Need brackets Can localize and initialize in one step ► my ($x, $y) By default, all variables are global Variables can be declared local with my function ► my $x; Variables declared with my are accessible only within enclosing block (usually until end of loop or subroutine) ► “lexical scoping”, like local variables in C ► Perl also has “dynamic scoping” like shell, uses local function Can localize more than one variable at once ► my ($x, # Need brackets Can localize and initialize in one step ► my ($x, $y) Llama3 pages 62-64; Camel3 pages ; perlfunc manpage
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 16 Timeout # Sum a variable-length list of numbers. # Read some numbers while (<>) { chomp; $_; } print "Sum is ", sum "\n"; sub sum { my $sum = 0; # Iterate over parameter foreach my $num # With local iterator $num. { $sum += $num; # Add this element to running total. } return $sum; } # Sum a variable-length list of numbers. # Read some numbers while (<>) { chomp; $_; } print "Sum is ", sum "\n"; sub sum { my $sum = 0; # Iterate over parameter foreach my $num # With local iterator $num. { $sum += $num; # Add this element to running total. } return $sum; }
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 17 Passing array parameters Arrays are flattened into lists before being put into parameter ► func($x, –$_[0] = x; $_[1] = y; ► sizes of arrays are lost in flattening ► array must be reconstructed by subroutine –e.g., my ($x, If passing one array to a subroutine, make it the last argument ► func($x, # Not $y) –elements $_[2] to end must be Don’t pass more than one array to a function won’t work because of list flattening –diff won’t know ends and begins ► can be solved using references (Topic 11) Arrays are flattened into lists before being put into parameter ► func($x, –$_[0] = x; $_[1] = y; ► sizes of arrays are lost in flattening ► array must be reconstructed by subroutine –e.g., my ($x, If passing one array to a subroutine, make it the last argument ► func($x, # Not $y) –elements $_[2] to end must be Don’t pass more than one array to a function won’t work because of list flattening –diff won’t know ends and begins ► can be solved using references (Topic 11) Camel3 pages 221,
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 18 Subroutines in built-in functions Anonymous subroutine bodies (“closures”) are used by some built-in Perl functions map { code ► “modify” operation: create a new list with code applied to each element grep { code ► “filter” operation: create a new list from only the elements where code is true sort { code ► custom sorting: use code to compare two elements of list to determine their sorted order Can also use closures in user-defined functions ► requires use of references (Topic 11) Anonymous subroutine bodies (“closures”) are used by some built-in Perl functions map { code ► “modify” operation: create a new list with code applied to each element grep { code ► “filter” operation: create a new list from only the elements where code is true sort { code ► custom sorting: use code to compare two elements of list to determine their sorted order Can also use closures in user-defined functions ► requires use of references (Topic 11) Llama3 pages , ; Camel3 pages 730, ; perlfunc manpage
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 19 Timeout # Censor: remove four-letter words from input. while (<>) { # Break line into words. # split function explained in topic = split /\s+/, $_; # Put only words which match the expression # (length not equal to 4) # $_ is each element in turn # (a bit like foreach loop = grep { length $_ != 4 print } # Censor: remove four-letter words from input. while (<>) { # Break line into words. # split function explained in topic = split /\s+/, $_; # Put only words which match the expression # (length not equal to 4) # $_ is each element in turn # (a bit like foreach loop = grep { length $_ != 4 print }
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 20 Timeout # Sorting a list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as = print "As # Sorting comparison routine (automatically given two # parameters $a and $b) can specify how items collate. # -1: $a precedes $b; +1: $a follows $b; 0: = sort { if ($a < $b) { return -1; } elsif ($a > $b) { return 1; } else { return 0; } print "As # Sorting a list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as = print "As # Sorting comparison routine (automatically given two # parameters $a and $b) can specify how items collate. # -1: $a precedes $b; +1: $a follows $b; 0: = sort { if ($a < $b) { return -1; } elsif ($a > $b) { return 1; } else { return 0; } print "As
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 21 Timeout # Sorting a list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as = print "As # Numerical sorting is so common there is # shorthand for it using the "spaceship" # operator which returns -1, 0 or = sort { $a $b print "As # Sorting a list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as = print "As # Numerical sorting is so common there is # shorthand for it using the "spaceship" # operator which returns -1, 0 or = sort { $a $b print "As
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 22 Perl debugger Perl has a built-in source-level debugger ► perl -d script...arguments... Most useful commands ► r (run) ► n (next line, skip through nested subroutines) ► s (step, stop at subroutine calls) ► b line (break when line reached) ► c (continue running) ► p expr (print expression) ► x list (examine list expression) ► l (list code) ► q (quit debugger) Perl has a built-in source-level debugger ► perl -d script...arguments... Most useful commands ► r (run) ► n (next line, skip through nested subroutines) ► s (step, stop at subroutine calls) ► b line (break when line reached) ► c (continue running) ► p expr (print expression) ► x list (examine list expression) ► l (list code) ► q (quit debugger) Llama3 page 294; Camel3 pages ; perldebug manpage
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 23 Covered in this topic Command-line arguments array The diamond operator <> ► related Subroutines ► declaring with sub ► calling ► returning from Local variables ► my function Built-in functions using closures ► map, grep, sort Perl debugger Command-line arguments array The diamond operator <> ► related Subroutines ► declaring with sub ► calling ► returning from Local variables ► my function Built-in functions using closures ► map, grep, sort Perl debugger
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 24 Going further Prototypes ► making user-defined subroutines behave more like builtins ► Camel3 pages Code generation ► building Perl code on the fly with eval ► Camel3 pages Built-in functions ► a myriad of standard subroutines provided by Perl ► Camel3 pages BEGIN and END ► special functions that run before or after other code (see also awk ) ► Camel3 pages Prototypes ► making user-defined subroutines behave more like builtins ► Camel3 pages Code generation ► building Perl code on the fly with eval ► Camel3 pages Built-in functions ► a myriad of standard subroutines provided by Perl ► Camel3 pages BEGIN and END ► special functions that run before or after other code (see also awk ) ► Camel3 pages
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 25 Next topic Hashes ► aka associative arrays ► arrays indexed by strings, not numbers Hash variables and functions Hashes ► aka associative arrays ► arrays indexed by strings, not numbers Hash variables and functions Llama3 chapter 5, pages Camel3 pages 76-78, , , perldata manpage