Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, 88-91 Programming Perl 3rd edition pages 80-83,

Similar presentations


Presentation on theme: "Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, 88-91 Programming Perl 3rd edition pages 80-83,"— Presentation transcript:

1 Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, 88-91 Programming Perl 3rd edition pages 80-83, 217-233, 659, 742-745 perlsub manpage

2 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

3 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 in @ARGV 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 because @ARGV ’s size is known ► if no command-line arguments, @ARGV 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 in @ARGV 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 because @ARGV ’s size is known ► if no command-line arguments, @ARGV is empty Llama3 pages 90-91; Camel3 page 659; perlvar manpage

4 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"; }

5 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

6 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

7 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; }

8 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.

9 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 217-218 ; perlsyn manpage

10 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 10 Calling subroutines  Subroutines officially begin with & character ► $thing is scalar, @thing 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 scalar, @thing 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

11 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 variable @_ ► argument list @_ is unrelated to default argument $_  Subroutine can access members of @_ 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 variable @_ ► argument list @_ is unrelated to default argument $_  Subroutine can access members of @_ to get parameter values ► sub weekday { ($y, $m, $d) = @_;... } ► sub weekday { $y = $_[0];... } Llama3 pages 60-62; Camel3 pages 219-221

12 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 { 3.1415926535898; }  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 { 3.1415926535898; }  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

13 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";

14 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";

15 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, $y, @result); # 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, $y, @result); # Need brackets  Can localize and initialize in one step ► my ($x, $y) = @_; Llama3 pages 62-64; Camel3 pages 132-136; perlfunc manpage

16 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 into @nums. while (<>) { chomp; push @nums, $_; } print "Sum is ", sum (@nums), "\n"; sub sum { my $sum = 0; # Iterate over parameter list @_. 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 into @nums. while (<>) { chomp; push @nums, $_; } print "Sum is ", sum (@nums), "\n"; sub sum { my $sum = 0; # Iterate over parameter list @_. foreach my $num (@_) # With local iterator $num. { $sum += $num; # Add this element to running total. } return $sum; }

17 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 array @_ ► func($x, $y, @array) –$_[0] = x; $_[1] = y; $_[2..@array+1] = @array; ► sizes of arrays are lost in flattening ► array must be reconstructed from @_ by subroutine –e.g., my ($x, $y, @array) = @_;  If passing one array to a subroutine, make it the last argument ► func($x, $y, @array) # Not func($x, @array, $y) –elements $_[2] to end must be from @array  Don’t pass more than one array to a function ► diff(@a, @b) won’t work because of list flattening –diff won’t know where @a ends and where @b begins ► can be solved using references (Topic 11)  Arrays are flattened into lists before being put into parameter array @_ ► func($x, $y, @array) –$_[0] = x; $_[1] = y; $_[2..@array+1] = @array; ► sizes of arrays are lost in flattening ► array must be reconstructed from @_ by subroutine –e.g., my ($x, $y, @array) = @_;  If passing one array to a subroutine, make it the last argument ► func($x, $y, @array) # Not func($x, @array, $y) –elements $_[2] to end must be from @array  Don’t pass more than one array to a function ► diff(@a, @b) won’t work because of list flattening –diff won’t know where @a ends and where @b begins ► can be solved using references (Topic 11) Camel3 pages 221,224-225

18 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 } @list ► “modify” operation: create a new list with code applied to each element  grep { code } @list ► “filter” operation: create a new list from only the elements where code is true  sort { code } @list ► 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 } @list ► “modify” operation: create a new list with code applied to each element  grep { code } @list ► “filter” operation: create a new list from only the elements where code is true  sort { code } @list ► 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 213-219, 236-238; Camel3 pages 730, 740-741; perlfunc manpage

19 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 7. @words = split /\s+/, $_; # Put only words which match the expression # (length not equal to 4) into @safewords. # $_ is each element of @words in turn # (a bit like foreach loop iterator). @safewords = grep { length $_ != 4 } @words; print "@safewords\n"; } # Censor: remove four-letter words from input. while (<>) { # Break line into words. # split function explained in topic 7. @words = split /\s+/, $_; # Put only words which match the expression # (length not equal to 4) into @safewords. # $_ is each element of @words in turn # (a bit like foreach loop iterator). @safewords = grep { length $_ != 4 } @words; print "@safewords\n"; }

20 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 20 Timeout # Sorting a list numerically @list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as strings. @alphabetically = sort @list; print "As strings: @alphabetically\n"; # Sorting comparison routine (automatically given two # parameters $a and $b) can specify how items collate. # -1: $a precedes $b; +1: $a follows $b; 0: equal @numerically = sort { if ($a < $b) { return -1; } elsif ($a > $b) { return 1; } else { return 0; } } @list; print "As numbers: @numerically\n"; # Sorting a list numerically @list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as strings. @alphabetically = sort @list; print "As strings: @alphabetically\n"; # Sorting comparison routine (automatically given two # parameters $a and $b) can specify how items collate. # -1: $a precedes $b; +1: $a follows $b; 0: equal @numerically = sort { if ($a < $b) { return -1; } elsif ($a > $b) { return 1; } else { return 0; } } @list; print "As numbers: @numerically\n";

21 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 21 Timeout # Sorting a list numerically @list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as strings. @alphabetically = sort @list; print "As strings: @alphabetically\n"; # Numerical sorting is so common there is # shorthand for it using the "spaceship" # operator which returns -1, 0 or +1 @numerically = sort { $a $b } @list; print "As numbers: @numerically\n"; # Sorting a list numerically @list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as strings. @alphabetically = sort @list; print "As strings: @alphabetically\n"; # Numerical sorting is so common there is # shorthand for it using the "spaceship" # operator which returns -1, 0 or +1 @numerically = sort { $a $b } @list; print "As numbers: @numerically\n";

22 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 506-517; perldebug manpage

23 Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 23 Covered in this topic  Command-line arguments ► @ARGV array  The diamond operator <> ► related to @ARGV  Subroutines ► declaring with sub ► calling ► returning from  Local variables ► my function  Built-in functions using closures ► map, grep, sort  Perl debugger  Command-line arguments ► @ARGV array  The diamond operator <> ► related to @ARGV  Subroutines ► declaring with sub ► calling ► returning from  Local variables ► my function  Built-in functions using closures ► map, grep, sort  Perl debugger

24 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 225-228  Code generation ► building Perl code on the fly with eval ► Camel3 pages 705-707  Built-in functions ► a myriad of standard subroutines provided by Perl ► Camel3 pages 677-830  BEGIN and END ► special functions that run before or after other code (see also awk ) ► Camel3 pages 480-485  Prototypes ► making user-defined subroutines behave more like builtins ► Camel3 pages 225-228  Code generation ► building Perl code on the fly with eval ► Camel3 pages 705-707  Built-in functions ► a myriad of standard subroutines provided by Perl ► Camel3 pages 677-830  BEGIN and END ► special functions that run before or after other code (see also awk ) ► Camel3 pages 480-485

25 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 73-85 Camel3 pages 76-78, 697-700, 703-704, 733-734 perldata manpage


Download ppt "Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, 88-91 Programming Perl 3rd edition pages 80-83,"

Similar presentations


Ads by Google