Passing Parameters by Reference
Learn the ways by which we can pass values to a subroutine by reference.
We'll cover the following
What is pass by reference?
When passing arguments by reference, the original value is passed. Therefore, the original value gets altered. In pass by reference, we actually pass the value and access them using $_[index]
where the index is the variable sequence passed. It tells the compiler that the data is a reference to the value rather than simply the value itself.
Example: swap numbers
Now let’s redefine the swap
subroutine from the example in the previous lesson.
sub swap{ #parameters num1 and num2 passed using pass by value method$temp = $_[0]; #creating a variable temp and setting equal to $_[0]$_[0] = $_[1]; #setting the value of $_[0] equal to $_[1]$_[1] = $temp; #setting the value of $_[1] equal to temp which is equal to $_[0]}$num1 = 4;$num2 = 5;# Have a careful look at this function callprint "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 illustrates how this subroutine works:
- The way the data is passed into
swap
is different from that in our previous example. - The called subroutine refers directly to
$num1
as$_[0]
and to$num2
as$_[1].
By making use of a reference type the copy of variables is no longer made, the data is changed in an actual variable.
As an analogy, think of asking someone to proofread and markup a printed document. You can either give them a photocopy (pass by value) or hand them the original document (pass by reference). In the same way, you can tell the compiler whether to pass a copy of the arguments or the original variables themselves depending on whether you want the originals to be changed or not.