The difference is that passing an array to a subroutine passes a copy of that array whereas a reference to an array you can dereference and get the actual array. Perhaps an example will help
#! perl -w use strict; my @array = ("0","1","2","3"); my $aref = \@array; print "Original array: ", @array, "\n"; print "Pass original array to testnonref(): "; testnonref(@array); print @array, "\n"; print "Running sub passing array reference and printing array:"; testref($aref); print @array, "\n"; sub testnonref { my @subarray = shift; $subarray[0] = "4"; } sub testref { my $one = shift; $$one[0] = "4"; }
Here I used your array and array reference (hases work the same way) and first I print out what the array looks like. Then I print out what the array looks like after passing it to the testnonref subroutine. Then I print out what it looks like after passing by reference. Hopefully the output will make it a little clearer:
Original array: 0123 Pass original array to testnonref(): 0123 Running sub passing array reference and printing array:4123
As you can see, passing by reference actually changes the value of your original array whereas just passing the array makes a copymakes a reference to your array using @_ and any changes are lost after the subroutine exits.
Update: thanks, I always assumed (incorrectly) that perl copied the array like other languages. This is why I love perlmonks... always learning better ways of doing things.
In reply to Re: Small troubles with references
by MCS
in thread Small troubles with references
by coldmiser
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |