Search code examples
perlpass-by-referencesubroutinepass-by-valuepass-by-pointer

Why do these blocks of code behave differently?


I am new to Perl, and I cannot figure this out. I have two seemingly identical sets of code, but one subroutine updates the value while another does not. In the first set of code, my understanding is that the reference to an array is passed, then the value at which that reference is pointing is updated. Then when leaving the subroutine, the value has been changed. However, in the second one, I would expect the same thing to occur. It does update the array, but then it forgets about it after leaving the subroutine. Can someone please explain to me what is going on behind the scenes with the second set of code?

First Code Set:

#!/usr/bin/perl -w

use strict;

{
    my @array = (1, 2, 3);
    removeSecondElement(\@array);
    print @array;  #output: 13
    print("\n");
}

sub removeSecondElement{
    my ($arrayReference) = @_;
    splice(@$arrayReference, 1, 1);
    print @$arrayReference;  #output: 13
    print "\n";
}

Second Code Set:

#!/usr/bin/perl -w

use strict;

{
    my @array = (1, 2, 3);
    removeSecondElement(\@array);
    print @array;  #output: 123
    print("\n");
}

sub removeSecondElement{
    my ($arrayReference) = @_;
    my @array = @$arrayReference;
    splice(@array, 1, 1);
    print @array;  #output: 13
    print "\n";
}

Solution

  • In the first example, you use the reference to get the array and then you modify that. There is only one array and you change it.

    In the second example, you use the reference to get the array, then you copy the content of the array into a second array, then you modify the second array. There are two arrays and you never alter the original one.