http://www.perlmonks.org?node_id=886415

sg has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

If a perl script gets access to a string, how can the script interpret the contents of the string as perl code and execute it? My naive attempt failed:

use diagnostics; use warnings; use strict; my $a_code =<<'CODE'; sub tryme { my $foo = shift; return $foo + 2; } CODE # Intent shown here does _not_ work my $ans = eval{ $a_code; tryme( 3 ); } or die "doesn't work";

The error might be in the way in which the code in being packaged into the string $a_code, or in how $a_code is being used, or in both.

Replies are listed 'Best First'.
Re: How to interpret a string as perl code and execute it?
by Corion (Patriarch) on Feb 05, 2011 at 16:28 UTC

    You want "string-eval", not "block-eval":

    my $ans = eval "$acode; tryme(3)"; if (my $err = $@) { die "Caught error: $err in code [$acode]"; };

      Thanks; string eval does work in the example. But the following bit more complex example, in which the string needs to use the "context" of the executing script, fails:

      use diagnostics; use warnings; use strict; my %h; $h{ 'a' }{ 'b' } = 5; my $b_code =<<'CODE'; sub tryme_b { my $foo = shift; return ${ $foo }{ 'a' }{ 'b' }; } CODE my $ans = eval "$b_code; tryme_b( \%h );" or die "[$b_code] doesn't wo +rk:$@"; print "b:$ans,\n";

        Would your code work when run stand-alone? Have you printed out the code you're trying to eval? Have you looked at the error message and looked at what causes it?

        The following change to your code might help you see the problem:

        use diagnostics; use warnings; use strict; use Data::Dumper; my %h; $h{ 'a' }{ 'b' } = 5; my $b_code =<<'CODE'; sub tryme_b { my $foo = shift; return ${ $foo }{ 'a' }{ 'b' }; } CODE my $c = "$b_code; tryme_b( \%h );"; my $ans = eval $c or die "[$c] doesn't work:$@"; print "b:$ans,\n";

        Also, basic debugging in your tryme_b would also show you what goes wrong.

        You didn't properly convert your Perl to code a Perl string literal. To generate the string
        tryme_b( \%h )
        you need the string literal
        "tryme_b( \\%h )"