B
Ben Morrow
Quoth ddtl said:If I define a "use strict" and want to create a closure,
how can I refer to the anonymous functions defined in that
closure? Consider the following example:
-------------------------------------------
use strict;
{
our $f = sub {print "Hi\n";};
}
&$f;
-------------------------------------------
Here compiler complains, and reports an error:
"Variable "$f" is not imported at ~/test line 7."
The variable declared by 'our' is a lexically-scoped alias to the
package global, so you need to put it in the same place as you would put
an equivalent 'my' variable. What you want is
use strict;
our $f;
{
# presumably there is more code here?
$f = sub {...};
}
# I prefer this style of indirect function call, as it matches the other
# deref ops and doesn't lead to potential confusion about calling named
# subs with &.
$f->();
or perhaps
our $f = do {
...
sub {...};
};
Ben