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

I have question about the function eval. When I run some code in it will the output of the code be displayed or be returned in a variable??? I have the documentation, and I still don't get it. =(

I am the first overweight, very tall munchkin... be very amazed.

Replies are listed 'Best First'.
RE: eval output
by Albannach (Monsignor) on Nov 10, 2000 at 20:45 UTC
    The return value of an eval() is simply the value of the last expression evaluated in the eval, or undef if there is an error. Is there something you want to do with an eval that you might want to explain?

    (update) Here's a simple example that should help you with the idea: perl -le "print eval(print 1+1)" produces:

    2 <-- printed within the eval() 1 <-- printed outside the eval()

    (further update)When I have a question like this, I just try it: perl -le "$i=5;print $i,eval('$i++;print $i;');print $i" produces:

    6 <-- printed outside the eval(), but AFTER it has run so $i has +been incremented 61 <-- 6 printed within the eval(), 1 printed outside 6 <-- printed in the next statement outside the eval()

    Conclusion: eval() operates within the context of the host program.

      What I am writing is a small indexing program for my website. Sort of similar to the function of Everything, but a little simpler. What I want is when someone pulls up "index.pl?webpage=main_page" that page is a CGI script, and I want to run, and have it display its output.

      I think I know how to do,a nd I was going to use eval -- instead of require. But does eval use variables that have already been declared before the eval has been called.

      Sorry this is a lot to ask, but you asked to explain it... Oh yeah Thanks...

      I am the first overweight, very tall munchkin... be very amazed.
        Any eval statement does its execution in the current context and scope. Any variables that are available to code in the current scope are also available to code you eval, and any changes to those variables done in your eval block persist after it's over.
        my $code = '$a = 2;'; # $a is meaningless here; it's just a string sub hi { my $a = 1; eval $code; print "$a\n"; # 2 }
RE: eval output
by snax (Hermit) on Nov 10, 2000 at 21:22 UTC
    I think the answer you are after is....it just runs the code in your current environment.
    $doit = "print"; $x = 3; $cmd = "$doit \$x"; eval($cmd)
    yields "3" as ouput; the $cmd variable is "print $x" which eval'ed in your context produces the "3" output.

    Is that what you were after?