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.
Explanation
The figure below illustrates how this subroutine works:
- The way the data is passed into
swapis different from that in our previous example. - The called subroutine refers directly to
$num1as$_[0]and to$num2as$_[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.