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 (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]"; };

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
Node Status?
node history
Node Type: note [id://886417]
help
Chatterbox?
[chacham]: I'm sure this is old, but i just came across it: If you put a million monkeys at a million keyboards, one of them will eventually write a Java program. The rest of them will write Perl programs.
[LanX]: lol
[Corion]: Woo hoo! A new Auralnauts episode!
LanX mean unfair and funny
[LanX]: but most java code looks like from one million monkey using eclipse. ..

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (13)
As of 2018-04-23 16:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?