O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.4. Arguments

Although subroutines that have one specific action are useful, a whole new level of usefulness becomes available when you can pass arguments to a subroutine. In Perl, the subroutine invocation is followed by a list within parentheses, causing the list to be automatically assigned to a special variable named @_ for the duration of the subroutine. The subroutine can access this variable to determine the number of arguments and the value of those arguments. For example:

sub say_hello_to {
    print "hello, $_[0]!\n"; # first parameter is target
}

Here, we see a reference to $_[0], which is the first element of the @_ array. Special note: as similar as they look, the $_[0] value (the first element of the @_ array) has nothing whatsoever to do with the $_ variable (a scalar variable of its own). Don't confuse them! From the code, it appears to say hello to whomever we pass as the first parameter. That means we can invoke it like this:

say_hello_to("world");                  # gives hello, world!
$x = "somebody";
say_hello_to($x);                       # gives hello, somebody!
say_hello_to("me")+  say_hello_to("you"); # and me and you

Note that in the last line, the return values weren't really used. But in evaluating the sum, Perl has to evaluate all of its parts, so the subroutine was invoked twice.

Here's an example using more than one parameter:

sub say {
    print "$_[0], $_[1]!\n";
}

say("hello","world");         # hello world, once again
say("goodbye","cruel world"); # silent movie lament

Excess parameters are ignored: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required