in reply to Preserve the value of original array
You could make a copy of the array in second(), but that wouldn't be very efficient if your array is large. If your real code is sufficiently similar to the example you could simply use a different array (or no array at all - just add values to the list that foreach iterates over). For example:
Either option should accomplish what you asked. If you don't want to modify the array in second(), don't modify the array. :-)sub second { my $num_ref = shift; my $sum = 0; my @newarray = ( 6 .. 10 ); # try one of these options # foreach ( @$num_ref, 6 .. 10 ) { foreach ( @$num_ref, @newarray ) { $sum += $_; } return $sum; }
HTH
Update: If you really do want to make a copy of the array, simply pass the array to the sub rather than passing an array ref:
or pass an array ref and then copy it into a new array:my $result = second( @num ); sub second { my ( @array ) = @_; # etc
Please note that simply copying the array reference will not work, as it is still a reference to the original array.my $result = second( \@num ); sub second { my ( $aref ) = @_; my @new_array = @$aref; # my $new_ref = [ @$aref ]; # alternative
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Preserve the value of original array
by Anonymous Monk on Feb 14, 2006 at 06:28 UTC | |
by ayrnieu (Beadle) on Feb 14, 2006 at 07:01 UTC |