1 / 24

Perl Chapter 6

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

Download Presentation

Perl Chapter 6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Perl Chapter 6 Functions

  2. 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 { ….}

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

  4. Textbook’s Style • function definitions first, then program.

  5. 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…)

  6. 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)

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

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

  9. 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);

  10. 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)

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

  12. @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

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

  14. $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);

  15. 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);

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

  17. Apply function to list of parameters sub do_list{ my @list = @ARG; … return @list; } ($count, $sum, @totals)=do_list($count, $sum, @totals); ARRAY LAST!

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

  19. predefined functions • abs, chr, exit, exp, ord, log, rand, sqrt • warn instead of die • ….

  20. 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;

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

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

  23. sub subp (\@$\@\%$){ my ($arrayRef1, $size, $arrayRef2, $hashRef, $scalar)=@ARG; } subp(@list, $size, @digits, %table, $tableSize);

  24. Future • Skip chapter 7 for now (Pattern Matching) • Did 8 • Go to 9 on Monday on CGI programming w/ Perl

More Related