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.


In reply to Re: Preserve the value of original array by bobf
in thread Preserve the value of original array by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.