topic 4:subroutines cse2395/cse3395 perl programming learning perl 3rd edition chapter 4, pages...

25
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

Upload: william-bennett

Post on 17-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 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,

Topic 4:SubroutinesTopic 4:Subroutines

CSE2395/CSE3395Perl Programming

CSE2395/CSE3395Perl 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

Page 2: 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,

2Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

In this topicIn 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

Page 3: 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,

3Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Command-line argumentsCommand-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

Page 4: 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,

4Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

TimeoutTimeout

#!/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";}

Page 5: 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,

5Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

FiltersFilters

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 <STDIN>

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 <STDIN>

Llama3 pages 88-90; Camel3 pages 80-83

Page 6: 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,

6Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

<> (diamond) operator<> (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 <STDIN>

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 <STDIN>

Page 7: 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,

7Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

TimeoutTimeout

#!/usr/bin/perl -w

# Unix cat program

while (<>){ print;}

#!/usr/bin/perl -w

# Unix cat program

while (<>){ print;}

Page 8: 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,

8Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

TimeoutTimeout

#!/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.

Page 9: 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,

9Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

SubroutinesSubroutines

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

Page 10: 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,

10Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Calling subroutinesCalling 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

Page 11: 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,

11Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Calling subroutinesCalling 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

Page 12: 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,

12Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Subroutine returnSubroutine 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

Page 13: 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,

13Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

TimeoutTimeout

# Compute the hypotenuse of a triangle

# Declare the subroutinesub hypotenuse{ # Return root of sum of squares. sqrt($_[0] * $_[0] + $_[1] * $_[1]);}

# Read two numbers.print "Enter first number: ";chomp ($a = <STDIN>);print "Enter second number: ";chomp ($b = <STDIN>);print "Hypotenuse is ", hypotenuse($a, $b), "\n";

# Compute the hypotenuse of a triangle

# Declare the subroutinesub hypotenuse{ # Return root of sum of squares. sqrt($_[0] * $_[0] + $_[1] * $_[1]);}

# Read two numbers.print "Enter first number: ";chomp ($a = <STDIN>);print "Enter second number: ";chomp ($b = <STDIN>);print "Hypotenuse is ", hypotenuse($a, $b), "\n";

Page 14: 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,

14Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

TimeoutTimeout

# Compute the hypotenuse of a triangle

# Declare the subroutinesub 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 = <STDIN>);print "Enter second number: ";chomp ($b = <STDIN>);print "Hypotenuse is ", hypotenuse($a, $b), "\n";

# Compute the hypotenuse of a triangle

# Declare the subroutinesub 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 = <STDIN>);print "Enter second number: ";chomp ($b = <STDIN>);print "Hypotenuse is ", hypotenuse($a, $b), "\n";

Page 15: 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,

15Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Local variables with myLocal 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

Page 16: 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,

16Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

TimeoutTimeout

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

Page 17: 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,

17Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Passing array parametersPassing 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

Page 18: 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,

18Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Subroutines in built-in functionsSubroutines 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

Page 19: 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,

19Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

TimeoutTimeout

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

Page 20: 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,

20Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

TimeoutTimeout

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

Page 21: 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,

21Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

TimeoutTimeout

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

Page 22: 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,

22Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Perl debuggerPerl 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

Page 23: 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,

23Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Covered in this topicCovered 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

Page 24: 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,

24Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

Going furtherGoing 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

Page 25: 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,

25Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University

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