develooper Front page | perl.perl5.porters | Postings from July 2009

Re: [perl #67694] List::Util attaching to the wrong $_ when usedinside given/when construct

Thread Previous | Thread Next
From:
Bram
Date:
July 24, 2009 10:16
Subject:
Re: [perl #67694] List::Util attaching to the wrong $_ when usedinside given/when construct
Message ID:
20090724191617.9cjn2e76okcksw04@horde.wizbit.be
Citeren Dave Mitchell <davem@iabyn.com>:

> On Tue, Jul 21, 2009 at 12:45:04PM +0200, Rafael Garcia-Suarez wrote:
>> Ah, you're right. The parser has this line :
>> switch  :       label GIVEN '(' remember mydefsv mexpr ')' mblock
>> where mydefsv is an empty rule that lexicalizes $_.
>> But then the code I pasted above could probably be simplified.
>
>
> So if I've understood this correctly, given() adds a lexical $_ to the
> scope, and there's a bug in List::Util::first in that it doesn't work with
> a lexical $_? So not a bug in given/smartmatch?

I'm not sure if 'bug' is the correct word.

What happens: (example with for instead of given)

#!/usr/bin/perl -l

for my $_ (1) {
   my $c = sub { print $_ };
   $c->();
}

sub foo {
   my $code = shift;
   $_ = "abc";
   $code->();
}
__END__

$c is a closure and closes over $_.
It then passes the code reference to the function foo which modifies  
the global $_ and calls the closure.

But: the closure closes over $_ so it will always uses the value 1...


There are, as fas as I can see, two solutions:

1) modify given() so it doesn't use a lexical $_.

2) update the documentation for given() and make it more explicit that  
it uses a lexical $_ and that every block/code reference inside it  
needs  our $_;  before using $_.


Best regards,

Bram



Thread Previous | 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