Subroutines
 
Subs
  • Can be defined anywhere in the source code.
     
  • Subroutines are always global. There are no local subroutines. (At least until we get into packages)
     
  • Recursion is supported.
Passing parameters
  • Any number of parameters can be passed.
     
  • All parms go into a special list called @_
    sub add() { return $_[0] + $_[1]; }
    print add( 47,23 ); # prints 70
    

     
  • @_ can be processed like any other list
    sub add() {
        my $sum = 0;
        for my $val ( @_ ) {
            $sum += $val;
            }   # for
        return $sum;
        }   # sub
    print add( 47, 23, 12, 1.5 ); # prints 83.5
    print add(); # prints 0
    
Return values
  • The last value in a function is the return value of the function.
     
  • Use the return to make the return value explicit.
     
  • Subs can return lists or scalars.
     
  • The wantarray() tells the sub the context in which it was called.
#!perl -w

use strict;

my @house = qw( 5x7 10x12 17x24 6x9 12x18 );

my @rooms = bigrooms( 100, @house );
print "Big rooms are: ", join( ", ", @rooms ), "\n";

my $footage = bigrooms( 100, @house );
print "Total size = $footage sq. ft.\n";

# Pull out only those rooms with more than 100 specified size
# In scalar context, return the total size of the rooms kept
# In list context, return the list of rooms that are big enough
sub bigrooms() {
    my $minsize = shift; # by default, shifts @_
    die "Minimum size must be greater than 0" unless ($minsize > 0);

    my $total = 0;
    my @keepers = ();
    for my $spec ( @_ ) {
        $spec =~ /^(\d+)x(\d+)$/ or die "Invalid room spec passed: $spec";
        my $sqft = $1 * $2;
        if ( $sqft >= $minsize ) {
            push( @keepers, $spec );
            $total += $sqft;
            }   # if
        }   # for
    if ( wantarray() ) {
        return @keepers;
    } else {
        return $total;
    }
}
Big rooms are: 10x12, 17x24, 12x18
Total size = 744 sq. ft.
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 >>>