I have used the method of passing arrays by reference to a subroutine so I can prevent them from being turned into one long array w/out problems...many times.
Now, however, I've come across the need to change the elements' values inside the subroutine, and I expected (because they are array refs) the values of those elements to be changed outside of the subroutine too. That is not happening though. Could somebody please point out my mistake.
Here is a sample script that illustrates my problem.
#!/usr/local/bin/perl ### Temp script to replicate oid_mod.pl ### use strict; my @a1 = qw(a b c); my @a2 = qw(d e f); foreach (@a2) { print "$_\n"; } changem(\@a1,\@a2); #pass-by-ref to allow extraction foreach (@a2) { print "$_\n"; } sub changem { my ($r1,$r2) = @_; my @arr1 = @{$r1}; my @arr2 = @{$r2}; print "BEFORE: $arr2[1]\n"; $arr2[1] = "q"; print "AFTER: $arr2[1]\n"; }
Expected Output:
d e f BEFORE: e AFTER: q d q f
Actual Output:
d e f BEFORE: e AFTER: q d e f
Why, when I print @a2 after the subroutine, has the value of $a2[1] not changed?
Thank you in advance.

In reply to Array references inside a subroutine 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.