duyet has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I have a problem with ref array which i have spent sometimes debugging it. I fixed it but still don't understand how this can happen. Below is a shorten version of the code:

my $ra = [ 'A', 'B', 'C' ]; print STDERR '1. ra = ' . Dumper( $ra ); test_ra( $ra ); print STDERR '2. ra = ' . Dumper( $ra ); exit; sub test_ra { my $data = shift; foreach my $item ( @{ $data } ) { $item = 'Z'; } }
After running the code:
1. ra = [ 'A','B','C' ] 2. ra = [ 'Z','Z','Z' ]

Apparently assigning some other value to $item modifies my ref array. This is something i'm not expecting. Off course when i copy the content of the array to another one (my @dup_array = @{$data}) and use it, the problem will disappeared.

Maybe i've overlooked something, but hopefully you can shine some light on the darkness.

TIA

PS: i'm using v5.8.8

Replies are listed 'Best First'.
Re: ref array being modified unexpectively
by davido (Cardinal) on Jul 29, 2011 at 08:52 UTC

    Yes, there are two things you're overlooking:

    In perlsyn you'll see that within a foreach loop, the loop iterator variable ($item) becomes an alias to each element in the array being looped over. So if you modify $item, you modify the corresponding element within the loop's array.

    Also, since you're passing a reference to test_ra(), the subroutine is not acting upon a copy of the array referred to by $ra, but rather, the same exact array. In other words, if you were to print scalar $ra and also print scalar $data, you would see that they're the same reference.


    Dave

Re: ref array being modified unexpectively
by moritz (Cardinal) on Jul 29, 2011 at 08:52 UTC

    The behavior you observe is to be expected, if one is sufficiently familiar with Perl 5.

    In particular none of the steps cause a copy of the array (hey, you're passing a reference after all!).

    Perhaps the most surprising point is that foreach my $item alises $item to the current list/array element. But again that's "works as designed".