in reply to Scope problem in closures with an eval statement

I believe the problem is that you use q (single quote) around the print "$str$k, thus the variables were not interpolated.

You should use qq (double quote) instead.
my $print = emphasizePrint(); $print->("Hello World"); ## Prints "Hello World!!" sub emphasizePrint { my $k = "!!\n"; return sub { my ($str) = @_; eval (qq{print "$str$k"}); print STDERR "Error: $@" if ($@); } }

Replies are listed 'Best First'.
Re^2: Scope problem in closures with an eval statement
by moritz (Cardinal) on Apr 15, 2008 at 08:55 UTC
    That's really a bad idea in the general case, because it won't work if $k has a string terminator in it:
    sub emphasizePrint { my $k = qq{"!!\n}; return sub { my ($str) = @_; eval (qq{print "$str$k"}); print STDERR "Error: $@" if ($@); } } __END__ Error: Can't find string terminator '"' anywhere before EOF at (eval 1 +) line 2.

    In the general case this opens lots of holes, which can be a security risk.

    I think that citromatik deliberately interpolated the variables at eval time, not prior to evaling the string.