Jan 4, 2007

Basic #13, Subroutines

subroutines in Perl is declared like this:

sub testSub{
print "Hello World\n";
}

A call to the subroutine is made with an & before the subroutine name, as in:

&testSub;
&testSub($_);
&testSub(5, $_);

Parameters passed to the subroutine can be referenced with @_, which have nothing to do with $_

e.g.

sub printArguments{
print "@_";
}

each individual parameter can also be referenced with $_[0], $_[1], etc
** again $_[0], $_[1] has nothing to do with $_

1 comment:

Wicked Web Programmers said...

Thanks for sharing.Did you know that if you pass \$a to a subroutine then in the subroutine the variable that receives that parameter receives a *reference* pointing to the $a scalar?