<div class="gmail_quote">On Tue, May 3, 2011 at 3:36 PM, Jason Rush <span dir="ltr"><<a href="mailto:jason%2Bkcpm@jlrush.com">jason+kcpm@jlrush.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div class="im">> The massive headaches that would ensue if my initial approach did what<br>
> I wanted are easy to imagine. Or are they? When an array variable<br>
> holds copies instead of aliases, as they usually do, there would be<br>
> difference.<br>
<br>
</div>Isn't it due to Q being pass-by-reference that allows you to assign<br>
$_[0] and have the value assigned to $a because it is the same memory<br>
location?<br>
<br>
If it was pass-by-copy and not pass-by-reference, the values from $a,<br>
$b, and $c would be passed in and Q would not have access to the<br>
memory locations for $a, $b, and $c and thus would not be able to<br>
store values there.<br><br></blockquote><div> </div><div>Right, in Perl, the values in @_ are aliased, which is effectively the same as pass-by-reference in other languages. Though, I tend to think of pass-by-reference in Perl as using explicit references, rather than aliasing. Aliasing only works as long as you use the @_ variable directly by slicing or using an index lookup. If you use an assignment, the alias is not copied. If you modify @_, itself, the aliasing may also go away. </div>
<div><br></div><div>For example, assigning to @_:</div><div><br></div><div>    @_ = qw( a b c );</div><div><br></div><div>eliminates aliasing entirely because @_ now refers to a completely different array. Subsequent, $_[0] won't do anything to the original parameters. </div>
<div><br></div><div>Also, you have to be careful when modifying aliased parameters. For example, if we make a small change to the original code:</div><div><br></div><div><meta charset="utf-8"><span class="Apple-style-span" style="border-collapse: collapse; font-family: arial, sans-serif; font-size: 13px; ">    perl -le 'sub Q{@_[0,1,2] = (7,6,5)}; Q(1,$b,$c); print qq[$a $b $c\n];'</span></div>
</div><div><br></div>Running that will get you:<div><br></div><div>    Modification of a read-only value attempted at -e line 1.</div><div><br></div><div>In general, I try to avoid changing @_ or working with it directly. In my experience, side-effects in parameters tends to lead to unintended consequences.</div>
<div><br>-- <br>Andrew Sterling Hanenkamp<br><a href="mailto:sterling@hanenkamp.com">sterling@hanenkamp.com</a><br>785.370.4454<br>
</div>