[Kc] subtle distinction that looks like a bug

Sterling Hanenkamp sterling at hanenkamp.com
Tue May 3 14:49:49 PDT 2011


On Tue, May 3, 2011 at 3:36 PM, Jason Rush <jason+kcpm at jlrush.com> wrote:

> > The massive headaches that would ensue if my initial approach did what
> > I wanted are easy to imagine. Or are they? When an array variable
> > holds copies instead of aliases, as they usually do, there would be
> > difference.
>
> Isn't it due to Q being pass-by-reference that allows you to assign
> $_[0] and have the value assigned to $a because it is the same memory
> location?
>
> If it was pass-by-copy and not pass-by-reference, the values from $a,
> $b, and $c would be passed in and Q would not have access to the
> memory locations for $a, $b, and $c and thus would not be able to
> store values there.
>
>
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.

For example, assigning to @_:

    @_ = qw( a b c );

eliminates aliasing entirely because @_ now refers to a completely different
array. Subsequent, $_[0] won't do anything to the original parameters.

Also, you have to be careful when modifying aliased parameters. For example,
if we make a small change to the original code:

    perl -le 'sub Q{@_[0,1,2] = (7,6,5)}; Q(1,$b,$c); print qq[$a $b $c\n];'

Running that will get you:

    Modification of a read-only value attempted at -e line 1.

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.

-- 
Andrew Sterling Hanenkamp
sterling at hanenkamp.com
785.370.4454
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/kc/attachments/20110503/e0911132/attachment.html>


More information about the kc mailing list