Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

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

by Corion (Patriarch)
on Feb 05, 2011 at 16:28 UTC ( [id://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]"; };

Replies are listed 'Best First'.
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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://886417]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-19 03:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found