This crops up often enough. Like mentioned, you shouldn't operate on $_ because it is an alias to the elements of the original data structure, and as such modifies them. Here is what cou can do:
my $original = [qw(alpha beta gamma)];
my @duplicate;
for (0..$#$original) {
my $temp = $original->[$_];
$temp = rand();
push @duplicate, $temp;
}
print "Original: $_\n" for (@$original);
print "Mofified: $_\n" for (@duplicate);
Which gives the expected, and desired:
Original: alpha
Original: beta
Original: gamma
Mofified: 0.421875
Mofified: 0.108734130859375
Mofified: 0.69537353515625
Update: Just to make things a bit more clear. I can obviously see that the original question is conserned with subroutine arguments being references. I merely expanded on the code that was attached as to not complicate the situation. Bull-blown examples with subroutines had already been posted prior to my reply. So fast to --?
Update: you might be also interested in this node, global $_ behavior which discusses up to some extent aliasing.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.