SlideShare a Scribd company logo
1 of 12
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

What's hot

Lecture 22
Lecture 22Lecture 22
Lecture 22
rhshriva
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 

What's hot (19)

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

Viewers also liked

Perl Intro 9 Command Line Arguments
Perl Intro 9 Command Line ArgumentsPerl Intro 9 Command Line Arguments
Perl Intro 9 Command Line Arguments
Shaun Griffith
 
Perl Intro 2 First Program
Perl Intro 2 First ProgramPerl Intro 2 First Program
Perl Intro 2 First Program
Shaun Griffith
 
Perl Intro 8 File Handles
Perl Intro 8 File HandlesPerl Intro 8 File Handles
Perl Intro 8 File Handles
Shaun Griffith
 
Perl Intro 5 Regex Matches And Substitutions
Perl Intro 5 Regex Matches And SubstitutionsPerl Intro 5 Regex Matches And Substitutions
Perl Intro 5 Regex Matches And Substitutions
Shaun Griffith
 
Perl Intro 3 Datalog Parsing
Perl Intro 3 Datalog ParsingPerl Intro 3 Datalog Parsing
Perl Intro 3 Datalog Parsing
Shaun Griffith
 

Viewers also liked (9)

Perl Intro 6 Ftp
Perl Intro 6 FtpPerl Intro 6 Ftp
Perl Intro 6 Ftp
 
Perl Intro 9 Command Line Arguments
Perl Intro 9 Command Line ArgumentsPerl Intro 9 Command Line Arguments
Perl Intro 9 Command Line Arguments
 
Perl Intro 4 Debugger
Perl Intro 4 DebuggerPerl Intro 4 Debugger
Perl Intro 4 Debugger
 
Perl Intro 2 First Program
Perl Intro 2 First ProgramPerl Intro 2 First Program
Perl Intro 2 First Program
 
Perl Intro 8 File Handles
Perl Intro 8 File HandlesPerl Intro 8 File Handles
Perl Intro 8 File Handles
 
Perl Intro 5 Regex Matches And Substitutions
Perl Intro 5 Regex Matches And SubstitutionsPerl Intro 5 Regex Matches And Substitutions
Perl Intro 5 Regex Matches And Substitutions
 
Perl Intro 3 Datalog Parsing
Perl Intro 3 Datalog ParsingPerl Intro 3 Datalog Parsing
Perl Intro 3 Datalog Parsing
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 

Similar to Perl Intro 7 Subroutines

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Scripting3
Scripting3Scripting3
Scripting3
Nao Dara
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Anton Shemerey
 

Similar to Perl Intro 7 Subroutines (20)

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
PHP Tips & Tricks
PHP Tips & TricksPHP Tips & Tricks
PHP Tips & Tricks
 
Object::Franger: Wear a Raincoat in your Code
Object::Franger: Wear a Raincoat in your CodeObject::Franger: Wear a Raincoat in your Code
Object::Franger: Wear a Raincoat in your Code
 
Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent. Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
 
Scripting3
Scripting3Scripting3
Scripting3
 
PHP 5 Boot Camp
PHP 5 Boot CampPHP 5 Boot Camp
PHP 5 Boot Camp
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tie
 
Dades i operadors
Dades i operadorsDades i operadors
Dades i operadors
 
35 Years of Open Source Software
35 Years of Open Source Software35 Years of Open Source Software
35 Years of Open Source Software
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)
 

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