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 (with the ampersand and the subroutine name) 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: although similar in appearance, 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! The code seems to say hello to whomever we pass as the first parameter. As a result, 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 ...

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.