Hi all
Suppose you have the following dummy example of a closure: (The real example I'm working on do a little more interesting thing.)
my $print = emphasizePrint(); $print->("Hello World"); ## Prints "Hello World!!" sub emphasizePrint { my $k = "!!\n"; return sub { my ($str) = @_; eval (q{print "$str$k"}); print STDERR "Error: $@" if ($@); } }
The problem is that this example doesn't work because the eval statement is compiled at run-time where it is called, that is outside of the emphasizePrint subroutine and there $k is out of scope, right?
The solution would be to include $k in the returned subroutine but outside the eval statement, avoiding $k to be "garbage-collected". The subroutine emphasizePrint would look like this:
sub emphasizePrint { my $k = "!!\n"; return sub { $k; ## <- INSERTED my ($str) = @_; eval (q{print "$str$k"}); print STDERR "Error: $@" if ($@); } }
But I'm not fully comfortable with this solution. Is this correct? Is there another (better) way of coping with this?
Thank you very much in advance
citromatik
In reply to Scope problem in closures with an eval statement by citromatik
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |