Anonymous subs
 
Passing subroutines
  • Referring to the sub without a parameter list gives a reference to the subroutine
     
  • The sort() function uses this mechanism to allow custom sorts.
Sort functions
  • Sort functions always have the variables $a and $b defined as the parms.
     
  • Comparisons use the three-way operators: cmp for strings, and <=> for numerics.
#!perl -w

use strict;

my @list = ( 5, 123, 42, 98.6 );
my @sorted1 = sort @list;
print "Default sort: @sorted1\n"; # not what we wanted

my @sorted2 = sort numerically @list;
print "Numerically:  @sorted2\n"; # Now we're happy

sub numerically { return $a <=> $b; }
Default sort: 123 42 5 98.6
Numerically:  5 42 98.6 123
Anonymous subs
  • An anonymous subroutine is a code block that doesn't have a name.
     
  • You can use an anonymous subroutine simply by referring to it.
    my @sorted3 = sort { $a <=> $b } @list;
    

     
  • You can also return an anonymous subroutine from a function, as in:
    sub sortstyle($) {
        if ( $_[0] eq "numerically" ) {
            return sub { $a <=> $b };
        } else {
            return sub { $a cmp $b };
        }
    my @sorted4 = sort sortstyle("numerically") @list;
    
Index
Introduction
What Is Perl?
Perl Resources
Running a Perl Program
Perl Thinking
Data Types
Scalars
Strings: Single Quoted
Strings: Double Quoted
Scalar operations
Scalar comparisons
Variables
Lists
Using Lists
Control Structures
Hashes
Hash Manipulation
File Handling
Regex Matching
Regex Matching: Ex. 1
Regex Matching: Ex. 2
Regex Replacing
Subroutines
Anonymous subs
References
Structures
Modules
Modules: File::Find
Modules: Internet
Modules: Win32::*
Everything Else
  Next page >>>