Closed p5pRT closed 21 years ago
If I run the program
use strict; sub factorial { my $fact = sub { my ($n) = @_; $n > 0 ? $n * $fact->($n-1) : 1; }; $fact->(@_); }
I get the error
Global symbol "$fact" requires explicit package name at fact.pl line 9.
The `perlsub' manpage states that
A "my" declares the listed variables to be confined (lexically) to the enclosing block\, conditional (if/unless/elsif/else)\, loop (for/foreach/while/until/continue)\, subroutine\, eval\, or do/require/use'd file.
so I think that either Perl's behavour should be changed to match the documentation\, or the documentation should be made clearer.
(I know that I can rewrite `factorial' as
sub factorial { my $fact; $fact = sub { my ($n) = @_; $n > 0 ? $n * $fact->($n-1) : 1; }; $fact->(@_); }
in order to get it to work as intended. That's not what this report is about.)
@iabyn - Status changed from 'open' to 'resolved'
Date: Fri\, 16 Jul 1999 15:24:38 +0100 If I run the program
use strict; sub factorial \{ my $fact = sub \{ my \($n\) = @​\_; $n > 0 ? $n \* $fact\->\($n\-1\) : 1; \}; $fact\->\(@​\_\); \}
I get the error
Global symbol "$fact" requires explicit package name at fact\.pl
line 9.
The `perlsub' manpage states that
A "my" declares the listed variables to be confined \(lexically\) to the enclosing block\, conditional \(if/unless/elsif/else\)\, loop \(for/foreach/while/until/continue\)\, subroutine\, eval\, or do/require/use'd file\.
so I think that either Perl's behavour should be changed to match the documentation\, or the documentation should be made clearer.
What you are seeing here is a more glorified version of
my $x = $x;
From perlsub.pod:
The declared variable is not introduced (is not visible) until after the current statement. Thus\,
my $x = $x;
can be used to initialize a new $x with the value of the old $x\, and the expression
my $x = 123 and $x == 123
is false unless the old $x happened to have the value C\<123>.
So the lexical $fact doesnt come into scope until the end of the assigment\, so the '$fact' seen within the anon sub is the global $::fact\, which doesn't exist.
Dave M.
notabug.
@iabyn - Status changed from 'open' to 'resolved'
Migrated from rt.perl.org#1005 (status was 'resolved')
Searchable as RT1005$