Perl | Pass By Reference


When a variable is passed by reference function operates on original data in the function. Passing by reference allows the function to change the original value of a variable.

When the values of the elements in the argument arrays @_ are changed, the values of the corresponding arguments will also change. This is what passing parameters by reference does.

In the example given below, when we update the elements of an array @a in subroutine sample, it also changes the value of the parameters which will be reflected in the whole program. Hence when parameters are called by reference, changing their value in the function also changes their value in the main program.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# Initialising an array 'a' 
@a = (0..10); 
  
# Array before subroutine call
print("Values of an array before function call: = @a\n");
  
# calling subroutine 'sample'
sample(@a);
  
# Array after subroutine call
print("Values of an array after function call: = @a");
  
# Subroutine to represent 
# Passing by Reference
sub sample
    $_[0] = "A";
  
    $_[1] = "B";
}

chevron_right


Output:



Values of an array before function call: = 0 1 2 3 4 5 6 7 8 9 10
Values of an array after function call: =  A B 2 3 4 5 6 7 8 9 10

Here is how the program works:-

  1. An array consisting of values from 0 to 10 is defined.
  2. Further, this array is passed to the ‘sample’ subroutine.
  3. A subroutine ‘sample’ is already defined. Inside this, the values of the first and second parameters are changed through the argument array @_.
  4. Values of the array @a are displayed after calling the subroutine. Now the first two values of the scalar are updated to A and B respectively.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# Initializing values to scalar
# variables x and y
my $x = 10;
my $y = 20;
  
# Values before subroutine call
print "Before calling subroutine x = $x, y = $y \n";
  
# Subroutine call
sample($x, $y);
   
# Values after subroutine call
print "After calling subroutine x = $x, y = $y ";
  
# Subroutine sample 
sub sample
{
    $_[0] = 1;
    $_[1] = 2;
}

chevron_right


Output:

Before calling subroutine x = 10, y = 20 
After calling subroutine x = 1, y = 2 


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.