[perl #62498] Scalar context breaks lvalue subs
authorFather Chrysostomos <sprout@cpan.org>
Wed, 1 Jun 2011 23:37:17 +0000 (16:37 -0700)
committerFather Chrysostomos <sprout@cpan.org>
Wed, 1 Jun 2011 23:38:10 +0000 (16:38 -0700)
commitbf8fb5ebdd40c5dae131bdfb08395be447f81573
tree5735a33a451fdff83e859f76829c4b503abbbe80
parent183eb698e2ceb8ab2d581de28f0b067e3c67af0d
[perl #62498] Scalar context breaks lvalue subs

That RT ticket reported that a $ prototype puts an implicit scalar()
on its argument, and that scalar(lvalue()) causes the function to
return a temporary value. In particular:

  ${\scalar($_)} = 1; # ok
  ${\scalar f()} = 1; # no effect

(where f is an lvalue sub that returns $_).

It turns out that this does not only affect scalar(), but also
|| and &&:

  ${\($_  && undef)} = 3; # ok
  ${\(f() && undef)} = 3; # no effect

Also, that comment in pp_leavesublv about f()->meth() not being lvalue
context is wrong, as

  $o->${\sub { $_[0] = "whatever" }};

assigns to $o, and

  sub UNIVERSAL::undef { undef $_[0] }

allows calls like

  $x->undef

to undefine $x, if it contains an object or package name.

Since copying values in rvalue context is wasteful anyway, since the
definition of rvalue context is that the value is going to be copied
(resulting in *two* copies), the easiest solution is not to copy val-
ues in rvalue context.

This ends up applying to what I call ‘reference’ context (semi-lvalue,
or potential lvalue) as well.

This works already with explicit return.

As a bonus, this also fixes bug #78680, for which there are already
to-do tests that were added before the bug was reported. See also:

http://www.nntp.perl.org/group/perl.perl5.porters/;msgid=20060118203058.GQ616@plum.flirble.org
pp_hot.c
t/op/sub_lval.t
t/re/pat_rt_report.t