develooper Front page | perl.perl5.porters | Postings from September 2014

[perl #20510] lvalue references would be nice

Thread Next
From:
Father Chrysostomos via RT
Date:
September 23, 2014 19:50
Subject:
[perl #20510] lvalue references would be nice
Message ID:
rt-4.0.18-2994-1411501843-1810.20510-15-0@perl.org
On Tue Sep 23 12:45:42 2014, sprout wrote:
> What about closures?
> 
> Should
> 
> my $x;
> sub { \$x = \$y }->();
> 
> affect the outer $x?
> 
> From a user’s standpoint, I would say yes.
> 
> But what about this?
> 
> our $y = 3;
> my $x;
> my $sub1 = sub { $x };
> sub { \$x = \$y };
> print &$sub1 // 'undef', "\n";  # 3 or undef?
> 
> ‘my $x; sub { foreach $x (...){...} }->()’ doesn’t do that, though.
> 
> In fact, when I implemented lexical subs, I introduced an
> inconsistency in this regard.
> 
> my sub foo { ... }
> eval ' sub foo { ... } ';
> 
> will clobber the outer &foo entry with the newly-defined sub.  But, as
> stated above, foreach $x only affects the innermost enclosing sub,
> ignoring the fact that the value comes from outside.  I think that the
> current behaviour of foreach is counterintuitive, which explains why
> nobody writes for $x when a lexical $x is in scope.  (This is also the
> subject of ticket #28396.)
> 
> If we were to change lexical subs to be consistent with the current
> foreach behaviour, then that eval example will no longer work.  The
> new definition of &foo will only be visible inside the eval.
> 
> If we want to go the other way and make foreach more intuitive (at
> least to me), then I don’t know how to implement it.  I’m sure I’ll
> come up with something, but I may break all the pad-related CPAN
> modules a second time.

Actually, foreach is less consistent than I thought:

#!perl

use feature 'state';

sub f {
  my $printx = shift;
  state $x = 3;
  if ($printx) {
    print "$x\n";
    return;
  }
  for $x (5) {
    f(1);
  }
}
f();

sub g {
  my $printx = shift;
  state $x = 3;
  if ($printx) {
    print "$x\n";
    return;
  }
  sub {
    for $x (5) {
      g(1);
    }
  }->()
}
g();
__END__

Output:
5
3


-- 

Father Chrysostomos


---
via perlbug:  queue: perl5 status: open
https://rt.perl.org/Ticket/Display.html?id=20510

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About