11.2. Passing Arguments
If a user wants to send values to a subroutine, he calls the function with a comma-separated list of arguments enclosed in parentheses.
The feed_me function below takes 3 arguments when called:
@fruit=qw(apples pears peaches plums); # Declare variables
$veggie="corn";
&feed_me( @fruit, $veggie, "milk" ); # Call subroutine with arguments
The arguments can be a combination of numbers, strings, references, variables, etc. They are received by the function in a special Perl array, called the @_ array, as a list of corresponding values called parameters.
sub feed_me{ print join(",", @_),"\n"; }
# Subroutine gets arguments in @_ array
Output: apples, pears, peache, plums, corn, milk
Call-by-Reference and the @_ Array
Arguments, whether scalar values or lists, are passed into the subroutine and stored in the @_ array. The @_ array is a local array whose values are implicit references to the actual parameters. If you modify the @_ array, you will modify the actual parameters. However, if you shift or pop off elements of the @_ array, you merely lose the reference to the actual parameters. (See "Call-by-Value with local and my" on page 332.)
When arrays or scalars are passed to a subroutine, the default in Perl is call-by-reference. The @_ is a special local array used for referencing the names of the formal arguments. Its values can be changed, thus changing the value of the actual parameters. The elements of the @_ array are $_[0], $_[1], $_[2], and so on. If a scalar variable is passed, its value is the first element of the @_ array, $_[0]. Perl doesn't care if you don't use all the parameters passed or if you have an insufficient number of parameters. If you shift or pop the @_ array, you merely lose your reference to the actual arguments. If you want to modify the global copy rather than the local @_ array, then you can use either typeglobs (symbolic references) or pointers (hard references). Hard references are discussed briefly in section 11.3.2 on page 349 and in more detail in Chapter 13, "Does This Job Require a Reference?"
Example 11.5.
(The Script)
#Passing arguments
1 $first="Charles";
$last="Dobbins";
2 &greeting ( $first, $last );
3 sub greeting{
4 print "@_", "\n";
5 print "Welcome to the club, $_[0] $_[1]!\n";

6 }
(Output)
4 Charles Dobbins
5 Welcome to the club, Charles Dobbins!
Scalars are assigned values. The greeting subroutine is called with two parameters, $first and $last. The subroutine is declared. The parameters are stored in the @_ array, a local array that is created when the subroutine is entered and is removed when the subroutine exits. It contains references to the $first and $last. The first two elements of the @_ array are printed. The individual elements are represented as scalars $_[0] and $_[1]. The closing curly brace marks the end of the subroutine definition. @_ will disappear.
|
Example 11.6.

The subroutine params is defined. The value of @_, the actual parameter list, is printed. @_ is a local array referencing any arguments passed to the subroutine. The first value of the @_ array is printed. The last element of the array is removed with the pop function and then printed. The foreach loop assigns, in turn, to scalar $value each element of the @_ array. Each element of the array is incremented by 5 and stored in the scalar $value. After the user has typed five numbers, the split function returns an array consisting of each of the numbers read from STDIN. The subroutine is called, passing the array as a parameter. The values printed illustrate that those values changed in the function were really changed. The only value that wasn't changed is the last element of the original array. The reference to it was popped in line 4 of the subroutine.
|
Call-by-Value with local and my
Most programming languages provide a way for you to pass arguments so that the original values are not altered by the subroutine. When an argument is passed using a call-by-value, a copy of the value of the argument is sent to the subroutine. If the copy is modified, the original value is untouched. To make copies of values in Perl, the arguments are copied from the @_ array and assigned to local variables. Perl provides two built-in functions, local and my, to create local copies.
The local Function
The local function was used to turn on call-by-value in Perl programs prior to the Perl 5 release. Now the my operator is used, which further ensures the privacy of variables within a function block.
The local function creates local variables from its list. Any variable declared with local is said to be dynamically scoped, which means it is visible from within the block where it was created and visible to any functions called from within this block or any blocks (or subroutines) nested within the block where it is defined. If a local variable has the same name as a global variable, the value of the global one is saved and a new local variable is temporarily created. When the local variable goes out of scope, the global variable becomes visible again with its original value(s) restored. After the last statement in a subroutine is executed, its local variables are discarded. It is recommended that all local variables be set at the beginning of the subroutine block.

Example 11.7.
(The Script)
1 $first="Per";
$last="Lindberg";
2 &greeting ( $first, $last ) ; # Call the greeting subroutine
3 print "---$fname---\n" if defined $fname; # $fname is local to
# sub greeting
# Subroutine defined
sub greeting{
4 local ($fname, $lname) = @_ ; # Call by value
5 print "Welcome $fname!!\n";
}
(Output)
3 <no output>
5 Welcome Per!!
The scalar variables are assigned values. A call is made to the greeting subroutine. Two arguments are passed. The print statement is not executed, because $fname is not defined here. It was defined as a local variable in the subroutine. It is local to the greeting subroutine. The local function takes a list of arguments from the @_ array and creates two local variables, $fname and $lname, from that list. The values in the local variables are copies of the values that were passed. This mechanism is called "pass by value." The print statement is executed. The contents of the local variable $fname are printed, which is a copy of what is in $first.
|
The my Operator
The my operator is also used to turn on call-by-value and is said to be lexically scoped. This means that variables declared as my variables are visible from the point of declaration to the end of the innermost enclosing block. That block could be a simple block enclosed in curly braces, a subroutine, eval, or a file. A variable declared with the my operator is created on a special scratch pad that is private to the block where it was created.
Unlike the variables declared with the local function, any variables declared as my variables are visible only within the subroutine in which they are declared, not in any subroutines called from this subroutine. If more than one variable is listed, the list must be enclosed in parentheses. So, the subroutine in Example 11.7 could have been written as follows:
sub greeting{
my ($fname, $lname) = @_; # $fname and $lname are private
print "Welcome $fname!!\n";
}
Example 11.8.
(The Script)
# The scope of my variables
1 my $name = "Raimo";
2 print "$name\n";
3 { # Enter block
4 print "My name is $name\n";
5 my $name = "Elizabeth";
6 print "Now name is $name\n";
7 my $love = "Christian";
8 print "My love is $love.\n";
9 } # Exit block
10 print "$name is back.\n";
11 print "I can't see my love,$love, out here.\n";
(Output)
2 Raimo
5 My name is Raimo
6 Now name is Elizabeth
8 My love is Christian.
10 Raimo is back.
11 I can't see my love,, out here.
The my operator is used to create a lexical variable $name assigned the value Raimo. The variable is visible from the place where it is created and within any inner blocks. It is placed on its own private scratch pad. The value of the lexical variable is printed. The lexical variable, $name, is still in scope; i.e., visible. A new lexical variable is declared. It gets its own private scratch pad. The new variable, $name, is visible and its value is printed. Another lexical variable is declared within the block and given its private scratch pad. The value of $love, Christian, is printed. It is visible within this block. The block ends here. The my variables will go out of scope. The value of the $name variable is now visible. Raimo is printed. The $love variable has gone out of scope.
|
Example 11.9.
Code View: (The Script)
# Difference between my and local
1 $friend="Louise"; # Global variables
2 $pal="Danny";
3 print "$friend and $pal are global.\n";
4 sub guests {
5 my $friend="Pat"; # Lexically scoped variable
6 local $pal="Chris"; # Dynamically scoped variable
7 print "$friend and $pal are welcome guests.\n";
8 &who_is_it; # Call subroutine
}
9 sub who_is_it {
10 print "You still have your global friend, $friend, here.\n";
11 print "But your pal is now $pal.\n"; # Dynamically scoped
}
12 &guests; # Call subroutine
13 print "Global friends are back: $friend and $pal.\n";
(Output)
3 Louise and Danny are global.
7 Pat and Chris are welcome guests.
10 You still have your global friend, Louise, here.
11 But your pal is now Chris.
12 Global friends are back: Louise and Danny.
The variable $friend is assigned a value, Louise. All variables are global within main. The variable $pal is assigned a value, Danny. It is also global. The values of the global variables are printed. The subroutine guests is defined. The my operator localizes the scalar $friend to this subroutine. The local function localizes the variable $pal to this and all subroutines called from here. The $friend and the $pal variables are printed in the guests subroutine. The subroutine who_is_it is called. The subroutine who_is_it is defined. In the subroutine who_is_it, the global variable $friend(Louise) is visible. The lexical variable $friend (Pat) is declared as a my variable in the calling subroutine and is not visible in this subroutine. The local scalar variable $pal (Chris), on the other hand, was defined in the guests subroutine and is still visible in this subroutine, who_is_it. The guests subroutine is called. After exiting the subroutines, the global variables are back in scope and their values printed.
|
Using the strict Pragma (my and our)
A pragma is a module that triggers a compiler to behave in a certain way. For example, if it detects something in your program it doesn't like, your program may be aborted. The strict pragma can be used to prevent the use of global variables in a program. When you use a global variable, even a variable declared with local, the compiler will complain if strict has been declared. Only lexically scoped variables are allowed. They are variables that are declared with either the my or our built-in functions. The our built-in (Perl 5.6+) is used when you need a global variable but still want to use the strict pragma to protect from the accidental use of global variables elsewhere in the program. (For more information about strict and packages, see "The strict Pragma" on page 403.)
Example 11.10.
(The Script)
1 use strict "vars";
2 my $name = "Ellie"; # my (lexical) variables are okay
3 @friends = qw(Tom Stefan Bin Marie);
# global variables not allowed
4 local $newspaper = "The Globe"; # local variables are not allowed
5 print "My name is $name and our friends are @friends.\n";
(Output)
3 Global symbol "@friends" requires explicit package name at
rigid.pl line 3.
4 Global symbol "$newspaper" requires explicit package name at
rigid.pl line 4.
In string, @friends now must be written as \@friends at rigid.pl
line 5, near "$name and our friends our @friends"
Global symbol "@friends" requires explicit package name at
rigid.pl line 5.
Execution of rigid.pl aborted due to compilation errors.
The strict pragma is used with vars as its argument. This tells the compiler to complain if it spots any global variables. The strict module, strict.pm, is part of the standard Perl distribution. The variable $name is a lexically scoped my variable, which means it is private to the block where it is created. The strict pragma likes my variables. The array @friends is a global variable. The compiler will complain when it sees global variables as shown in line 3 of the output. By explicit package name, the message is saying that you can still use this global variable if you precede its name with the package name and two colons; in other words, @main::friends is acceptable. Perl classifies variables declared with the local function as dynamically allocated global variables. The compiler again complains because the variable is not declared with my. To still use the local variable, explicit means local $main::newspaper. Due to compiler errors, the program never gets this far.
|
Example 11.11.
(The Script)
1 use strict "vars";
2 my $name = "Ellie"; #All variables are lexical in scope
3 our @friends = qw(Tom Stefan Bin Marie);
4 our $newspaper = "The Globe";
5 print "$name and $friends[0] read the $newspaper.\n";
(Output)
5 Ellie and Tom read the The Globe.
The strict pragma is declared with vars as its argument. This tells the compiler to complain if it spots any global variables. The strict module, strict.pm, is part of the standard Perl distribution. The variable $name is a lexically scoped my variable; in other words, it is private to the block where it is created. The strict pragma likes my variables. An our variable (Perl 5.6.0+) is disguised as a lexically scoped variable, so the strict pragma overlooks it. This allows you to get away with using a global variable if you really need one. The scalar is also an our variable. It is global and lexical, bypassing compiler warnings caused by the strict pragma. The print function displays the values of the lexical variables.
|
11.2.1. Prototypes
A prototype, also described as a template, tells the compiler how many and what types of arguments the subroutine should get when it is called. It lets you treat your subroutine just like a Perl built-in function. The prototype is made part of a declaration and is handled at compile time. To call subroutines that have been declared with a prototype, the ampersand (&) must be omitted, or the subroutine will be treated like a normal user-defined subroutine rather than as a built-in, and the compiler will ignore the prototype.
Prototype: (Perl 5.003+)
sub subroutine_name($$);
Takes two scalar arguments
sub subroutine_name(\@);
Argument must be an array, preceded with an @ symbol
sub subroutine_name($$;@)
Takes two scalar arguments and an optional array.
Anything after the semi-colon is optional.
Example 11.12.
# Filename: prototypes
# Testing prototyping
1 my $a=5;
my $b=6;
my $c=7;
2 @list=(100,200,300);
3 sub myadd($$) { # myadd requires two scalar arguments
my($x, $y)=@_;
print $x + $y,"\n";
}
4 myadd($a, $b); # Okay
5 myadd(5, 4); # Okay
6 myadd($a, $b, $c); # Too many arguments
(Output)
6 Too many arguments for main::myadd at prototypes line 14,
near "$c)" Execution of prototypes aborted due to compilation
errors.11
Three scalar variables are declared and assigned values. The array @list is assigned values. The subroutine myadd is prototyped. Two scalar values are expected as parameters. Any more or less will cause a compiler error. The subroutine is passed two scalar variables. This is okay. The subroutine is passed two numbers. This is okay. The subroutine was prototyped to take two scalars, but three are being passed here. The compiler sends an error message.
|
Example 11.13.
# Prototypes
1 sub mynumbs(@$;$); # Declaration with prototype
2 @list=(1,2,3);
3 mynumbs(@list, 25);
4 sub mynumbs(@$;$) { # Match the prototypes
5 my ($scalar)=pop(@_);
6 my(@arr) = @_;
7 print "The array is: @arr","\n";
8 print "The scalar is $scalar\n";
}
(Output)
7 The array is: 1 2 3
8 The scalar is: 25
This is a declaration with a prototype, asking for an array, a scalar, and an optional scalar. The semicolon is used to indicate that the argument is optional. The array @list is assigned values. The mynumbs subroutine is called with a list and a scalar value, 25. Don't use an ampersand when calling prototyped subroutines. The subroutine is defined. Even though the declaration of the subroutine on line 1 established the prototype, it must be repeated again here or the following error will appear: Prototype mismatch: sub main::mynumbs (@$;$) vs none at prototype line 19. The last element from the @_array is popped off and assigned to $scalar. The rest of the @_array is assigned to @arr. The values of the array @arr are printed. The value of $scalar is printed.
|
11.2.2. Return Value
The subroutine can act like a function when it is called; the function returns a scalar or a list. For example, a subroutine may be called from the right-hand side of an assignment statement. The subroutine can then send back a value to be assigned to a variable, either scalar or array.
$average = &ave(3, 5, 6, 20);
returned value call to subroutine
The value returned is really the value of the last expression evaluated within the subroutine.
The return function can also be used to return a specified value or to return early from the subroutine based on some condition. If used outside a subroutine, the return function causes a fatal error. You could say that the return is to a subroutine what an exit is to a program. If you use the exit function in a subroutine, you will exit the entire program and return to the command line.
Example 11.14.
(The Script)
#!/bin/perl
sub MAX {
1 my($max) = shift(@_);
2 foreach $foo ( @_ ){
3 $max = $foo if $max < $foo;
print $max,"\n";
}
print "------------------------------\n";
4 $max;
}
sub MIN {
my($min) = pop( @_ );
foreach $foo ( @_ ) {
$min = $foo if $min > $foo;
print $min,"\n";
}
print "------------------------------\n";
return $min;
}
5 my $biggest = &MAX ( 2, 3, 4, 10, 100, 1 );
6 my $smallest= &MIN ( 200, 2, 12, 40, 2, 20 );
7 print "The biggest is $biggest and the smallest is $smallest.\n";
(Output)
3
4
10
100
100
------------------------------
200
2
2
2
2
------------------------------
7 The biggest is 100 and the smallest is 2.
The scalar $max is assigned the value of the first element in the array @_. The my operator makes $max local to this subroutine. If $max is modified, the original copy is not affected. For each element in the list, the loop will assign, in turn, an element of the list to the scalar $foo. If $max is less than $foo, $max gets $foo. Since the last statement executed in subroutine MAX is $max, the value of $max is returned and assigned to $biggest at line 5. The scalar $biggest is assigned the value of the last expression in the MAX subroutine. The scalar $smallest is assigned the return value from function MIN. The return function is explicitly used in subroutine MIN.
|
11.2.3. Context and Subroutines
We introduced "context" when discussing variables and operators. Now we will see how context applies to subroutines. There are two main contexts: scalar and list. When mixing data types, results differ when an expression is evaluated in one or the other context.
A good example of context is in array or scalar assignment. Consider the following statements:
@list = qw( apples pears peaches plums ); # List context
$number = @list; #Scalar context
In list context, @list is assigned an array of the elements, but in scalar context, $number, produces the number of items in the array @list.
We have also seen context when using built-in Perl functions. Consider the localtime function. If the return value is assigned to a scalar, the date and time are returned as a string, but if the return value is assigned to an array, each element of the array represents a numeric value for the hour, minute, second, etc. The print function, on the other hand, expects to receive a list of arguments, list context. The built-in scalar function can be used to explicitly evaluate an expression in a scalar context as shown in Example 11.15.
Example 11.15.
# Context
1 @now = localtime; # List context
2 print "@now\n"; # Scalar context
3 $now = localtime;
4 print "$now\n";
5 print localtime, "\n"; # prints in list context
6 print scalar localtime,"\n"; # Forced to scalar context
(Output)
2 30 40 9 23 3 107 1 112 1
4 Mon Apr 23 09:40:30 2007
5 2021123310711121
6 Mon Apr 23 11:02:20 2007
|
Example 11.16.
# Context
1 print "What is your full name? ";
2 ($first, $middle, $last)=split(" ", <STDIN>);# STDIN scalar context
3 print "Hi $first $last.\n";
(Output)
2 What is your full name? Daniel Leo Stachelin
3 Hi Daniel Stachelin.
|
The wantarray Function and User-Defined Subroutines
"He took that totally out of context...." something you might say after hearing an argument based on a news story, the Bible, or a political speech. In Chapter 5, we discussed context, in Perl, which refers to how a variable and values are evaluated. For example, is the context list or scalar? There may be times when you want a subroutine to behave in a certain way based on the context in which it was called. This is where the built-in wantarray function can be used. You can use this function to determine whether the subroutine should be returning a list or a scalar. If your subroutine is called in list context (i.e., the return value will be assigned to an array), then wantarray will return true; otherwise, it will return false. If the context is to return no value (void context), wantarray returns the undefined value.
Example 11.17.
Code View: #!/usr/bin/perl
print "What is your full name? ";
chomp($fullname=<STDIN>);
1 @arrayname = title($fullname); # Context is array
print "Welcome $arrayname[0] $arrayname[2]!\n";
print "What is the name of that book you are reading? ";
chomp($bookname=<STDIN>);
2 $scalarname = title($bookname); # Context is string
print "The book $arrayname[0] is reading is $scalarname.\n";
3 sub title{
# Function to capitalize the first character of each word
# in a name and to return a string or an array of words
4 my $text=shift;
my $newstring;
5 my$text=lc($text);
6 my @newtext=split(" ", $text); # Create a list of words
foreach my $word ( @newtext ){
$word = ucfirst($word); # Capitalize the first letter
7 $newstring .= "$word "; # Create a title string
}
@newarray = split(" ", $newstring);
8 # Split the string into an array
chop($newstring); # Remove trailing whitespace
9 return wantarray ? @newarray : $newstring; # Return either array
# or scalar based on how the subroutine was called
}
(Output)
What is your full name? robert james taylor
Welcome Robert Taylor!
What is the name of that book you are reading? harry potter half
blood prince
The book Robert is reading is Harry Potter Half Blood Prince.
|