1.10.2 A Subroutine with Parameters

We now write a subroutine that takes parameters. The fact that the same subroutine can be called with different values of parameters is powerful. It allows us to indentify a subroutine with a task that can be invoked differently, as appropriate for the context. We explain with an example.

Program 1.17

#!/usr/bin/perl
#file subhello1.pl

######################
#main program starts
use strict;
my $name;

#some invocations or calls
$name = "Reeves";
hello1 ($name);

#Second call
$name = "Dulu";
hello1 ($name);

#Third call
$name = "Nicole";
hello1 ($name);


##################################
#Main program ends; subroutine section below
#Another subroutine that says hello.
#This one takes arguments. Arguments are put in the @_ variable

sub hello1 {
    my ($friend);
    $friend = $_[0];

    print "How are you doing $friend?...\n";
}

Let us first look at subroutine invocations. There are three calls and each one is the same although the value assigned to the variable used in the calls is different every time. Every time, the subroutine is invoked with one parameter only: $name. Actually, the subroutine is called with a list that contains one element. The list is ($name) containing only one element. When a subroutine is executed, this list of parameters from the call is available inside the subroutine in a special list variable @_. Use of @_ is the mechanism by which parameters are passed to a subroutine.

In the beginning of the hello1 subroutine, we declare a variable $friend with my. The $friend variable is available only inside the subroutine and not outside. We then set the scalar variable $friend to the 0th element of the parameter list @_. The zeroth element of @_ is obtained by writing $_[0]. Thus, the statements

my ($friend);

$friend = $_[0];

declare the variable $friend to be available within the subroutine and then assigns it the only value contained in the list @_. The variable $friend can be manipulated inside the subroutine without affecting anything outside.

The output of the program is given below.

How are you doing Reeves?...
How are you doing Dulu?...
How are you doing Nicole?...