develooper Front page | perl.perl5.porters | Postings from April 2007

Re: [perl #42695] very strange closure problem

Thread Previous | Thread Next
From:
demerphq
Date:
April 24, 2007 01:09
Subject:
Re: [perl #42695] very strange closure problem
Message ID:
9b18b3110704240109q6ce35bddp266cd06936804890@mail.gmail.com
On 4/24/07, via RT Andrew White <perlbug-followup@perl.org> wrote:
> # New Ticket Created by  Andrew White
> # Please include the string:  [perl #42695]
> # in the subject line of all future correspondence about this issue.
> # <URL: http://rt.perl.org/rt3/Ticket/Display.html?id=42695 >
>
>
> This is a bug report for perl from aewhite@uark.edu,
> generated with the help of perlbug 1.35 running under perl v5.8.7.
>
>
> -----------------------------------------------------------------
> Strange things have happened before but this is the best...
> Basicly, anonymous functions in package subs break on returning
> vars that are in the package scope unless the var is referenced
> somewhere in the package sub.
>
> This is best explained by code. Compare print_A_broken and
> print_A_strange. Follows is bar.pl and Foo.pm
>
> ##bar.pl##
> #!/usr/bin/perl -wT
>
> use strict;
>
> use lib ('.');
> use Foo;
>
> Foo::print_A_ok();
> Foo::print_A_broken();
> Foo::print_A_strange();
>
> ##Foo.pm##
> package Foo;
> use strict;
>
> my $varA = 'A';
>
> sub print_A_ok { print "Works ", $varA, "\n" };
> sub print_A_broken {
>   my %funcs = ( 'A' => sub {return $varA;});
>   print "Broken ", $funcs{'A'}(), "\n";
> };
> sub print_A_strange {
>   my %funcs = ( 'A' => sub {return $varA;} );
>   $varA = $varA; # this line fixes it!? WTF Also a print $varA fixes it!?
>   print "Strange ", $funcs{'A'}(), "\n";
> };
>
> return 1;
>
> ##output##
> Works A
> Use of uninitialized value in print at Foo.pm line 13.
> Broken
> Strange A
>
> Sorry if this is a repeat. I couldn't find anything that was
> still open on the site, but I could have missed it. Also, I
> hope this isn't a feature ;)

Its is a known issue, and no it isnt a feature. I believe this is on
somebodys todo list and may even be fixed in blead. (dont have blead
handy to check, but somebody is bound to follow up on this post and
clarify the situation)

The workaround is as you described, merely ensure that the outer sub
mentions the var at least once.

Cheers,
yves

-- 
perl -Mre=debug -e "/just|another|perl|hacker/"

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