SlideShare a Scribd company logo
Perl Brown Bag


             Subroutines
              Closures


               Shaun Griffith
              April 24, 2006

05/13/12         ATI Confidential   1
Agenda
•Subs
     •Basics
     •Arguments
     •Return values

•Closures
     •Static variables
     •Anonymous subs
05/13/12                       2
Subs
Basics
     sub my_sub
     { code goes here } # no semi-colon

Calling
     my_sub( arg1, arg2, …);
     $catch = my_sub();
     @stuff = my_sub(@args);

Ambiguous
     my_sub @args; # must be defined earlier
     &my_sub; # current @_ available inside


05/13/12                                       3
Arguments
Passing Args
     my_sub( “one”, $two, @three, %four );

Catching Args
     sub my_sub
     { my $x1 = shift @_;
           my $x2 = shift; # @_ is default
           my $x3 = shift; # reference
           my %x4 = @_; # all the rest
     … }

With a long list, that’s a lot of work!
05/13/12                                      4
Try It And See™
Do this on your own machine:
     Save the file sub1.pl on you PC
     go to Start, Run, cmd (to get to DOS)
     cd to the directory with sub1.pl
     perl –d sub1.pl
     > s
Now use <enter> to step through the program, and x
$var to examine variables at key places.




05/13/12                                             5
Try It And See™…
Now answer these questions:
     •Did you get “Odd number of elements…”? What does that
     mean? How did it happen?
     •What’s odd about %four in the second call to simple?
     •Why doesn’t print %four do what you expect?
     •Why isn’t smart all that good?
     •Is smarter better?
     •What happens if smarter gets a parameter it doesn’t
     know? What is it missing?




05/13/12                                                      6
Recursion
Factorial
     sub fac
     {
           my $x = shift;
           # exit conditions
           return if ( $x < 0 ); # bad input
           return 1 if ( ($x == 0) or ($x == 1));
           my $y = $x * fac($x-1);
           return $y;
     }
return $y could be written as just $y, since the last expression evaluated will
be returned in the absence of an explicit return.
05/13/12                                                                          7
Return
How many values should the sub return?
     0: return;
     1: return $x;
     list: return( $x, $y); # parens are better
     ref: return @array;
Here’s a gotcha:
     Sometimes you want to signal an error or an empty result,
     so you might try returning undef:
           return undef;
     However, in list context, undef is a one-element list:
           if ( scalar( @x = ( undef ) ) )…
     This is always true!!!
05/13/12                                                         8
Return with Context
wantarray (should have been named “wantlist”):
     sub check_context
     {     if (not defined wantarray)
           {      print “void” }
           elsif ( wantarray )
           {      print “list” }
           else
           {      print “scalar” }
           print “ contextn”;
     }

(For a more complete mechanism, see the Want module.)


05/13/12                                                9
Closures
Closures “enclose” lexical (my) variables.
Recall sub fac – once fac(317)is computed, there’s no
reason to compute it again, is there? One use of closures is for
simple cache variables:
     { # closure for fac
        my %cache; # only visible to fac, but “static”
        sub fac
        {
            my $x = shift;
            return if ( $x < 0 ); # bad input
            return 1 if ( ($x == 0) or ($x == 1));
            if ( not exists( $cache{$x} ) )
            {     $cache{$x} = $x * fac($x-1); }
            return $cache{$x};
        } # end sub fac
     } # end closure for fac
Closures must be defined above the first call!
05/13/12                                                           10
Anonymous Subs
Create a sub with no name (but save it as a coderef):
     my $two = 2;
     my $times_2 = sub { $two * shift };
     $z = $times_2->(17);
Note that $two is “captured” in the anonymous sub – as long as
$times_2 exists, so will $two.
The uglier syntax for this is:
     $z = &$times_2(17); # less clear
& is the sub sigil, like $ is for scalars.




05/13/12                                                         11
Next Time?
Filehandles?
     •Open
     •Close
     •EOF
     •Pipes
Command Line Arguments?
     •Catching
     •Checking
     •Using

05/13/12                      12

More Related Content

PPTX
Php & my sql
DOCX
PERL for QA - Important Commands and applications
PPT
Php variables
PDF
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PDF
The Origin of Lithium
PDF
Melhorando sua API com DSLs
PPTX
PHP Traits
Php & my sql
PERL for QA - Important Commands and applications
Php variables
PHPCon 2016: PHP7 by Witek Adamus / XSolve
The Origin of Lithium
Melhorando sua API com DSLs
PHP Traits

What's hot (19)

PDF
Learning Perl 6
PDF
Lecture 22
PDF
Sorting arrays in PHP
PDF
What's New in Perl? v5.10 - v5.16
PDF
Learning Perl 6 (NPW 2007)
PDF
Lithium: The Framework for People Who Hate Frameworks
PPTX
PHP Functions & Arrays
PDF
08 Advanced PHP #burningkeyboards
PDF
SPL: The Missing Link in Development
PDF
How to write code you won't hate tomorrow
PDF
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
PPTX
Introduction in php part 2
PDF
Neatly folding-a-tree
PPTX
PPTX
PHP PPT FILE
PDF
Web 4 | Core JavaScript
PDF
Text in search queries with examples in Perl 6
PPTX
Introduction in php
PDF
Generating Power with Yield
Learning Perl 6
Lecture 22
Sorting arrays in PHP
What's New in Perl? v5.10 - v5.16
Learning Perl 6 (NPW 2007)
Lithium: The Framework for People Who Hate Frameworks
PHP Functions & Arrays
08 Advanced PHP #burningkeyboards
SPL: The Missing Link in Development
How to write code you won't hate tomorrow
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Introduction in php part 2
Neatly folding-a-tree
PHP PPT FILE
Web 4 | Core JavaScript
Text in search queries with examples in Perl 6
Introduction in php
Generating Power with Yield
Ad

Viewers also liked (9)

PPT
Perl Intro 6 Ftp
PPT
Perl Intro 9 Command Line Arguments
PPT
Perl Intro 4 Debugger
PPT
Perl Intro 2 First Program
PPT
Perl Intro 8 File Handles
PPT
Perl Intro 5 Regex Matches And Substitutions
PPT
Perl Intro 3 Datalog Parsing
PDF
Study: The Future of VR, AR and Self-Driving Cars
PDF
Hype vs. Reality: The AI Explainer
Perl Intro 6 Ftp
Perl Intro 9 Command Line Arguments
Perl Intro 4 Debugger
Perl Intro 2 First Program
Perl Intro 8 File Handles
Perl Intro 5 Regex Matches And Substitutions
Perl Intro 3 Datalog Parsing
Study: The Future of VR, AR and Self-Driving Cars
Hype vs. Reality: The AI Explainer
Ad

Similar to Perl Intro 7 Subroutines (20)

PDF
Scripting3
PDF
Marc’s (bio)perl course
PDF
PDF
Perl_Part6
PDF
Perl_Part5
PDF
Perl intro
PDF
Introduction to Perl
PDF
tutorial7
PDF
tutorial7
PDF
newperl5
PDF
newperl5
PDF
Tutorial perl programming basic eng ver
PPTX
Bioinformatica p4-io
PDF
Perl intro
ODP
Red Flags in Programming
ODP
WTFin Perl
PPTX
Lecture 3 Perl & FreeBSD administration
PDF
Advanced perl finer points ,pack&amp;unpack,eval,files
PPT
Basic perl programming
Scripting3
Marc’s (bio)perl course
Perl_Part6
Perl_Part5
Perl intro
Introduction to Perl
tutorial7
tutorial7
newperl5
newperl5
Tutorial perl programming basic eng ver
Bioinformatica p4-io
Perl intro
Red Flags in Programming
WTFin Perl
Lecture 3 Perl & FreeBSD administration
Advanced perl finer points ,pack&amp;unpack,eval,files
Basic perl programming

Perl Intro 7 Subroutines

  • 1. Perl Brown Bag Subroutines Closures Shaun Griffith April 24, 2006 05/13/12 ATI Confidential 1
  • 2. Agenda •Subs •Basics •Arguments •Return values •Closures •Static variables •Anonymous subs 05/13/12 2
  • 3. Subs Basics sub my_sub { code goes here } # no semi-colon Calling my_sub( arg1, arg2, …); $catch = my_sub(); @stuff = my_sub(@args); Ambiguous my_sub @args; # must be defined earlier &my_sub; # current @_ available inside 05/13/12 3
  • 4. Arguments Passing Args my_sub( “one”, $two, @three, %four ); Catching Args sub my_sub { my $x1 = shift @_; my $x2 = shift; # @_ is default my $x3 = shift; # reference my %x4 = @_; # all the rest … } With a long list, that’s a lot of work! 05/13/12 4
  • 5. Try It And See™ Do this on your own machine: Save the file sub1.pl on you PC go to Start, Run, cmd (to get to DOS) cd to the directory with sub1.pl perl –d sub1.pl > s Now use <enter> to step through the program, and x $var to examine variables at key places. 05/13/12 5
  • 6. Try It And See™… Now answer these questions: •Did you get “Odd number of elements…”? What does that mean? How did it happen? •What’s odd about %four in the second call to simple? •Why doesn’t print %four do what you expect? •Why isn’t smart all that good? •Is smarter better? •What happens if smarter gets a parameter it doesn’t know? What is it missing? 05/13/12 6
  • 7. Recursion Factorial sub fac { my $x = shift; # exit conditions return if ( $x < 0 ); # bad input return 1 if ( ($x == 0) or ($x == 1)); my $y = $x * fac($x-1); return $y; } return $y could be written as just $y, since the last expression evaluated will be returned in the absence of an explicit return. 05/13/12 7
  • 8. Return How many values should the sub return? 0: return; 1: return $x; list: return( $x, $y); # parens are better ref: return @array; Here’s a gotcha: Sometimes you want to signal an error or an empty result, so you might try returning undef: return undef; However, in list context, undef is a one-element list: if ( scalar( @x = ( undef ) ) )… This is always true!!! 05/13/12 8
  • 9. Return with Context wantarray (should have been named “wantlist”): sub check_context { if (not defined wantarray) { print “void” } elsif ( wantarray ) { print “list” } else { print “scalar” } print “ contextn”; } (For a more complete mechanism, see the Want module.) 05/13/12 9
  • 10. Closures Closures “enclose” lexical (my) variables. Recall sub fac – once fac(317)is computed, there’s no reason to compute it again, is there? One use of closures is for simple cache variables: { # closure for fac my %cache; # only visible to fac, but “static” sub fac { my $x = shift; return if ( $x < 0 ); # bad input return 1 if ( ($x == 0) or ($x == 1)); if ( not exists( $cache{$x} ) ) { $cache{$x} = $x * fac($x-1); } return $cache{$x}; } # end sub fac } # end closure for fac Closures must be defined above the first call! 05/13/12 10
  • 11. Anonymous Subs Create a sub with no name (but save it as a coderef): my $two = 2; my $times_2 = sub { $two * shift }; $z = $times_2->(17); Note that $two is “captured” in the anonymous sub – as long as $times_2 exists, so will $two. The uglier syntax for this is: $z = &$times_2(17); # less clear & is the sub sigil, like $ is for scalars. 05/13/12 11
  • 12. Next Time? Filehandles? •Open •Close •EOF •Pipes Command Line Arguments? •Catching •Checking •Using 05/13/12 12