Next: File I/O
Up: CGI Scripts with Perl
Prev: Pattern Matching

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/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
Up: CGI Scripts with Perl
Prev: Pattern Matching

[HOME] The Geometry Center Home Page

Comments to: webmaster@www.geom.uiuc.edu
Created: May 08 1996 --- Last modified: May 29 1996