citromatik has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Scope problem in closures with an eval statement
by moritz (Cardinal) on Apr 14, 2008 at 11:02 UTC | |
by ysth (Canon) on Apr 15, 2008 at 06:57 UTC | |
|
Re: Scope problem in closures with an eval statement
by Fiftyvolts (Novice) on Apr 14, 2008 at 13:23 UTC | |
|
Re: Scope problem in closures with an eval statement
by ysth (Canon) on Apr 15, 2008 at 07:01 UTC | |
|
Re: Scope problem in closures with an eval statement
by dwindura (Novice) on Apr 15, 2008 at 08:42 UTC | |
by moritz (Cardinal) on Apr 15, 2008 at 08:55 UTC |