develooper Front page | perl.perl5.porters | Postings from November 2010

Re: [perl #79908] my $x; sub(){$x} makes a constant even if $xchanges

Thread Previous | Thread Next
November 29, 2010 12:40
Re: [perl #79908] my $x; sub(){$x} makes a constant even if $xchanges
Message ID:
Dave Mitchell wrote:
>What do you think is the bug? It seems to be behaving the way I expect.

The code looks like it closes over the lexical variable $x.  That lexical
variable is then set to 6, so when the closure is later called (through
the &foo name) it would be expected for it to return 6.  This is how
closures normally work, both in other languages, and in Perl when that
particular form with the () prototype is not used.  For the closure
operation to return a constant-5 sub cannot be justified by reference
to closure theory; it can only be explained as a special exception in
Perl semantics, which is what it is.

The generation of optimised constant subs is a useful facility.
It certainly ought to be available, without having to invoke the
installation-in-a-package behaviour of "use constant".  But this exception
to the closure rules is a poor way to make it available, since it breaks
an otherwise logically consistent language feature.  In my opinion,
constant-sub creation should be made available via an XS function in some
CPAN module (very easily arranged), and the magic behaviour of sub(){$x}
should be phased out (less easy, probably requiring a deprecation cycle).


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About