
| Contents |
|||||||||||||||||||||||||||||
| [an error occurred while processing this directive] |
7.3 Using ArgumentsA 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,
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 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
|