Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: How to interpret a string as perl code and execute it?

by Corion (Pope)
on Feb 05, 2011 at 16:28 UTC ( #886417=note: print w/ replies, xml ) Need Help??


in reply to How to interpret a string as perl code and execute it?

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

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


Comment on Re: How to interpret a string as perl code and execute it?
Download Code
Re^2: How to interpret a string as perl code and execute it?
by sg (Pilgrim) on Feb 05, 2011 at 17:03 UTC

    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 )"

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://886417]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2014-08-30 02:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (291 votes), past polls