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:

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; }
Either option should accomplish what you asked. If you don't want to modify the array in second(), don't modify the array. :-)

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:

my $result = second( @num ); sub second { my ( @array ) = @_; # etc
or pass an array ref and then copy it into a new array:
my $result = second( \@num ); sub second { my ( $aref ) = @_; my @new_array = @$aref; # my $new_ref = [ @$aref ]; # alternative
Please note that simply copying the array reference will not work, as it is still a reference to the original array.

Replies are listed 'Best First'.
Re^2: Preserve the value of original array
by Anonymous Monk on Feb 14, 2006 at 06:28 UTC
    Thanks, bobf

    I need to pass the array as a reference because I'm passing more than one value. My example was simplified to make my question simpler.

      It's a little bit harder to answer when your example is thus simplified. It looks like you got your answer, anyway.

      (I might've suggested:)

      sub second { my $sum = 0; $sum += $_ for 6, @{+shift}; $sum }