Passing Parameters by Value

Learn how to pass the value of actual parameters to a subroutine.

Perl allows us to pass arguments into a subroutine in two ways:

  • Pass by Value
  • Pass by Reference

Let’s take a look at the pass by value method.

Arguments passed by value

On passing arguments by value, the value of the argument may change within a subroutine, but the original value outside the subroutine remains unchanged. That means a duplicate of the original value is passed as an argument.

Example: a cube of a number

Consider the following program that accepts a number and prints its cube:

Press + to interact
sub cube {
my $num1 = @_[0]; #num1 parameter passed by value here
return $num1 * $num1 * $num1; #cube of num1 returned
}
$answer = cube(3); #function cube called with 3 passed as the argument
print $answer ;

Explanation

In the example above, we use the pass by value method to pass the parameter $num1 into the subroutine cube. We have used the keyword my before $num1 which limits the scope of $num1 in this subroutine. The subroutine then returns the cube of this value and $num1 goes out of scope and is destroyed.

Example: swap numbers

Now let’s look at a more complex case where the pass by value method won’t work.

Press + to interact
sub swap{ #parameters num1 and num2 passed using pass by value method
my $a = @_[0];
my $b = @_[1];
my $temp = $a; #creating a variable temp and setting equal to arg2
$a = @_[1]; #setting the value of arg2 equal to arg1
$b = $temp; #setting the value of arg1 equal to temp which is equal to arg2
}
$num1 = 4;
$num2 = 5;
# Have a careful look at this function call
print "num1 is: $num1\n";
print "num2 is: $num2\n";
print "\nAfter swapping\n\n";
swap($num1,$num2);
print "num1 is: $num1\n";
print "num2 is: $num2";

Explanation

The figure below shows how this subroutine works:

We probably thought that the subroutine would work, $a would be 5 and $b would be 4. However, that is clearly not the case, the output is the opposite because the scope of the variables is local and deleted at the end of the subroutine.