240 likes | 314 Views
Perl Chapter 6. Functions. Subprograms. In Perl, all subprograms are functions returns 0 or 1 value although may have “side-effects” optional function declaration heading, no code sub fn_name; function definition heading, has code can be ANYWHERE, except inside another function
E N D
Perl Chapter 6 Functions
Subprograms • In Perl, all subprograms are functions • returns 0 or 1 value • although may have “side-effects” • optional function declaration • heading, no code sub fn_name; • function definition • heading, has code • can be ANYWHERE, except inside another function sub fn_name { ….}
declaration C:\>perl C:\>perl sub print_header; print_header(); print_header(); sub print_header{ sub print_header{ print “\n Hello\n”; print “\n Hello\n”; } } ^Z ^Z Output: Hello Hello Note: If function declaration used, can call print_header; #with no ()s call definition
Textbook’s Style • function definitions first, then program.
Value returning functions • Two ways • predefined function return • returns value of last expression evaluated sub foo { sub foo { return (expr); expr; } } (1) (2) • return function can be called anywhere in function (and in more than one place, but…)
Context of function call • context of call (scalar or list) dictates context of evaluation of returned value def: sub sub1{ @result =(1,3,5); } call: $scalar = sub1(); #$scalar assigned 3 @list = sub1(); #@list assigned (1,3,5)
Scope and Lifetime • scope – range of statements over which variable is visible (spatial concept) • lifetime – begins when created and ends when no longer can be used (temporal concept) • global scope • variable visible in whole program file • not good inside a function (name conflicts)
2 kinds of Local variables • my – static local • just inside function or block • local – dynamic local • inside function or block and any functions called within block • dangerous sub sub1{ my $sum=0; # scope of static local $sum … # is just function sub1 }
Advantage: local variables give slightly faster access than global variables • For readability - declare local variables at beginning of function • To disallow non-static scoped variables use strict ‘vars’; #also forces all program #variables to be declared • my is a function in some situations my ($a, @list) = (3,2,7,6);
Parameters • actual parameters (arguments) • specified in call to a function • formal parameters • variables in function corresponding to actuals • pass by value • pass by reference (2 ways)
Pass by reference – 1st way • Done through implicit array variable @_ or @ARG • For @ARG (use statement use English; in program) • At time of call, values of actual parameters are copied into @ARG • At time of return, values from @ARG copied back.
@list =(1,3,5); fun (6, @list); sub fun{ #@ARG (6,1,3,5) … } • if hash flattened into array (better to pass by reference 2nd way) • number of actual doesn’t have to match number of formals • too many, ignores • too few, undef
sub addto{ $ARG[0] += $ARG[1]; } $a=5; addto($a, 7); • What is $a now? • What happens if we try to change $ARG[1]? 12 ignores it, can’t change 7
$ARG[0]=7 8 [1]=1 2 [2]=3 [3]=5 $x now 8 @list now (2,3,5) sub adder{ ++$ARG[0]; ++$ARG[1]; } $x=7; @list=(1,3,5); adder($x, @list); sub swap{ ($ARG[1], $ARG[0] = ($ARG[0], $ARG[1]); } swap ($a, $b);
Pass by value • Copy @ARG’s values to static locals sub sub1{ my ($x, $y, $z) = @ARG; … } • passing hashes by value – make it ONLY parameter sub sub1{ my %my_people = @ARG; … } … sub1(%people);
Passing references as parameters – 2nd way • pass references to actual parameters • ref to array single scalar assigned to @ARG • array copies ALL elements to @ARG sub do_array{ my $ref_list = $ARG[0]; … } … do_array (\@list); #same with a hash \%table
Apply function to list of parameters sub do_list{ my @list = @ARG; … return @list; } ($count, $sum, @totals)=do_list($count, $sum, @totals); ARRAY LAST!
indirect calls • if you have one of five different functions to be called depending on a string value of scalar variable • simulated switch or • construct hash of string key => address of function
predefined functions • abs, chr, exit, exp, ord, log, rand, sqrt • warn instead of die • ….
sort function (again) • additional parameter specifies comparison operator sort @list; #default was ascending cmp on strings • for numbers, use <=> as comparison operator • array of numbers in ascending order @list = sort {$a <=> $b;} @list; #book typo • array of numbers in descending order @list = sort{$b <=> $a;} @list; • array of strings in descending order @list = sort{$b cmp $a;} @list;
Handout • A subroutine defined or declared without parameter list can be called without any restrictions on the number or type of parameters passed • A subroutine defined with a parameter list MUST be called with exactly the parameters specified or compilation error results
Sample parameter lists • () zero parameters required or accepted • ($) 1 scalar parameter required • ($; \@) 1 scalar parameter required, 2nd parameter optional, but must be array (reference) • ($$$@) First 3 scalar, remaining actual put in ending put in ending array • (\@\%$;$$) array reference, hash reference, scalar, 2 optional scalars
sub subp (\@$\@\%$){ my ($arrayRef1, $size, $arrayRef2, $hashRef, $scalar)=@ARG; } subp(@list, $size, @digits, %table, $tableSize);
Future • Skip chapter 7 for now (Pattern Matching) • Did 8 • Go to 9 on Monday on CGI programming w/ Perl