Node:Using Arguments, Previous:Returning Values, Up:Subroutines



Using Arguments

A subroutine is not much good if you cannot give it input on which to operate. Of course, Perl allows you to pass arguments to subroutines just like you would to native Perl functions.

At the start of each subroutine, Perl sets a special array variable, @_, to be the list of arguments sent into the subroutine. By standard convention, you can access these variables through $_[0 .. $#_]. However, it is a good idea to instead immediately declare a list of variables and assign @_ to them. For example, if we want to greet a particular group of people, we could do the following:

     use strict;
     sub HowdyEveryone {
        my($name1, $name2) = @_;
        return "Hello $name1 and $name2.\n" .
               "Where do you want to go with Perl today?\n";
     }
     print &HowdyEveryone("bart", "lisa");
     

Note that since we used my, and we are in a new block, the variables we declared will live only as long as the subroutine execution.

This subroutine leaves a bit to be desired. It would be nice if we could have a custom greeting, instead of just "Hello". In addition, we would like to greet as many people as we want to, not just two. This version fixes those two problems:

     use strict;
     sub HowdyEveryone {
        my($greeting, @names) = @_;
        my $returnString;
     
        foreach my $name (@names) {
            $returnString .= "$greeting, $name!\n";
        }
     
        return $returnString .
               "Where do you want to go with Perl today?\n";
     }
     print &HowdyEveryone("Howdy", "bart", "lisa", "homer", "marge", "maggie");
     

We use two interesting techniques in this example. First of all, we use a list as the last parameter when we accept the arguments. This means that everything after the first argument will be put into @names. Note that had any other variables followed @names, they would have remained undefined. However, scalars before the array (like $greeting) do receive values out of @_. Thus, it is always a good idea to only make the array the last argument.