Perl: empty variable when using eval in a stream

I had a problem updating my project from perl 5.8.8 to perl 5.18.2.
I brought the problem to the following example:

use threads;

my $key = "abcdef";

print "test1 key = $key.\n";

my $thr = threads->create(sub {
    eval "print \"test2 key = \$key.\n\";";
}); 

$thr->join();

In perl 5.8.8 this gives the correct result:

test1 key = abcdef.
test2 key = abcdef.

But with perl 5.18.2, I have:

test1 key = abcdef.
test2 key = .

I tried other versions of perl and the problem seems to have appeared with 5.14.0 release. I am looking for a better way to fix this problem, as well as an explanation of this perl beaver modification.

I found several alternatives, but none of them work for me:

  • using "our key" instead of "my $ key"; but it makes the variable "more open."
  • "my $toto = $key;" eval ( $ eval); - (, , ,...) $ , eval, , . .

$key \$key eval , .

+4
2

. . PerlMonks. , , . sub, :

my $thr = threads->create(sub {
    $key;  # Create a closure.
    eval "print \"test2 key = \$key.\n\";";
}); 

, , :

my $sub = do {
    my $key = "abcdef";
    print "test1 key = $key.\n";
    sub {
        $key; # <-- Comment this line to get no value.
        eval "print \"test2 key = \$key.\n\";";
    }
};

$sub->();
+4

Perl eval.

  • eval EXPR Perl.

  • eval BLOCK . try .

, , .

0

All Articles