in reply to Small troubles with references
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Small troubles with references
by duff (Parson) on Feb 09, 2006 at 20:25 UTC | |
by demerphq (Chancellor) on Feb 09, 2006 at 20:33 UTC | |
by ptum (Priest) on Feb 09, 2006 at 23:08 UTC | |
by demerphq (Chancellor) on Feb 09, 2006 at 23:17 UTC | |
by runrig (Abbot) on Feb 09, 2006 at 23:15 UTC |