Presenting Mathematical Concepts on the World Wide Web
Forms & Scripts

Perl: Subroutines

Subroutines are important in Perl. Since Perl is not a structured programming language, the responsibility is on the programmer to make readable, modifiable, modular code. That means subroutines.
#!/usr/local/bin/perl

sub density {

    local($line, $char) = @_;
    local($num);

    @junk = split(/$char/, $line);

    $num = $#junk;
    $num++ if ($line =~/^$char/);
    $num++ if ($line =~/$char$/);

    return sprintf("%3.2f \n", $num / length($line));
}

print &density("This is a test", 't');
print &density("This is a test", 'a');

Local variables

To create local variables inside a subroutine block, use the local() operator.

When a subroutine is called with arguments, they are stored in a special array variable @_. Typically a subroutine will grab its arguments and store them in local variables.


Next: File I / O
Back: Pattern Matching
Up: Forms & Scripts


Presenting Mathematical Concepts on the World Wide Web. Copyright © 1997 by Carol Scheftic. All rights reserved. (This section was originally copyrighted in 1996 by The Geometry Center and is re-used here with permission.) Please send comments on this page, or requests for permission to re-use material from this page, to: scheftic@geom.umn.edu
Page established 1-Jun-97; last updated Thursday, 24-Jul-1997 01:25:00 CDT.