In this third part of a six-part article series on subroutines and functions in Perl, you'll learn about passing arguments into functions, and implicitly and explicitly getting return values. This article was excerpted from chapter six of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X).
As well as being set pieces of code to be executed whenever we need them, we can also use our user-defined functions just like Perl’s built-in functions—we can pass arguments (aka parameters) to the subroutine and expect an answer back.
Just like with Perl’s built-ins, we pass parameters by placing them between the parentheses:
my_sub(10,15);
What happens to them there? Well, they end up in one of Perl’s special variables, the array@_, and from there we can get at them. We’ll illustrate this with a subroutine that takes a list of values, adds them up, and prints the total. This example,total1.pl, contains a function namedtotal()that loops through the argument list@_and sums the arguments passed in:
#!/usr/bin/perl -w # total1.pl
use strict;
total(111, 107, 105, 114, 69); total(1...100); sub total { my $total = 0; $total += $_ foreach @_; print "The total is $total\n"; }
And to see it in action:
$ perl total1.pl The total is 506 The total is 5050 $
This program illustrates that we can pass any list to a subroutine, just like we can toprint(). When we do so, the list ends up in@_, where it’s up to us to do something with it. Here, we go through each element of it and add them up:
$total += $_ foreach @_;
This is a little cryptic, but it’s how you’re likely to see it done if written by an experienced Perl programmer. You could write this a little less tersely as follows:
my @args = @_; foreach my $element (@args) { $total = $total + $element; }
In the first example,@_would contain(111, 107, 105, 114, 69), and we’d add each value to$totalin turn.