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 { ….}
C:\>perl sub print_header;print_header();sub print_header{ print “\n Hello\n”; print “\n Hello\n”;}^Z Output:Hello Note: If function declaration used, can call print_header; #with no ()s declaration call definition
Textbook’s Style function definitions first, then program.
Value returning functions Two ways 1.predefined function return 2.returns value of last expression evaluatedsub 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 =(1,3,5); } call: $scalar = sub1(); #$scalar assigned = sub1(); 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 1.my – static local just inside function or block 2.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 = (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 – 1 st way Done through implicit array (use statement use English; in program) At time of call, values of actual parameters are copied At time of return, values copied back.
@list =(1,3,5); fun sub fun{ (6,1,3,5) … } if hash flattened into array (better to pass by reference 2 nd 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
sub adder{ ++$ARG[0]; ++$ARG[1]; } $ARG[0]=7 8 [1]=1 2 [2]=3 [3]=5 $x now now (2,3,5) sub swap{ ($ARG[1], $ARG[0] = ($ARG[0], $ARG[1]); } swap ($a, $b);
Pass by value values to static locals sub sub1{ my ($x, $y, $z) … } passing hashes by value – make it ONLY parameter sub sub1{ my %my_people … } … sub1(%people);
Passing references as parameters – 2 nd way pass references to actual parameters – ref to array single scalar assigned – array copies ALL elements sub do_array{ my $ref_list = $ARG[0]; … } … do_array #same with a hash \%table
Apply function to list of parameters sub do_list{ … } ($count, 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 #default was ascending cmp on strings for numbers, use as comparison operator array of numbers in ascending = sort {$a #book typo array of numbers in descending = sort{$b array of strings in descending = sort{$b cmp
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, 2 nd 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, } %table, $tableSize);
Future Skip chapter 7 for now (Pattern Matching) Did 8 Go to 9 on Monday on CGI programming w/ Perl