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

perl's do 'string' and eval 'string' seems to me equivalent except that 'eval' trapps an error while 'do' don't

can someone please show me what their differences are?:(

  • Comment on What is the difference between eval and do?

Replies are listed 'Best First'.
Re: What is the difference between eval and do?
by Eliya (Vicar) on Feb 19, 2011 at 14:53 UTC

    Well, one difference is that do 'string' interprets 'string' as a file name, while eval 'string' interprets 'string' as Perl code:

    $ perl -e 'do "print qq(foo\n)" or die qq($! $@)' No such file or directory at -e line 1. $ perl -e 'eval "print qq(foo\n)" or die qq($! $@)' foo

    There are also other more subtle differences (such as do cannot see lexical variables in the enclosing scope, while eval can), but - believe it or not - it's all in the docs: do, eval :)

      OK, This clears me up. Thanks:)
Re: What is the difference between eval and do?
by ELISHEVA (Prior) on Feb 19, 2011 at 21:36 UTC

    Note: I wrote this and only after realized that I didn't read eliya's answer carefully enough. Consider this an amplification of his final paragraph.

    There is a very nice summary of the difference in the documentation for do - see the second example for do EXPR.

    One of the biggest differences is that the code run by eval can "see" the value of my variables in the code surrounding it. When do "some file" executes the code in a file, that code lives in its own world and cannot access those variables.

      and this too, thanks:)
Re: What is the difference between eval and do?
by educated_foo (Vicar) on Feb 19, 2011 at 14:35 UTC
    You're asking "X and Y are equivalent except Z. Can you tell me how they are not equivalent?" My answer is "Z".

      I kinda meant "there be any other significant difference between X and Y beside Z?"

      I guess I should have said it that way in the first place, though. :(

Re: What is the difference between eval and do?
by Anonymous Monk on Feb 19, 2011 at 14:53 UTC
    seems to me equivalent exce

    Why does it seem to you that way, is it because the documentation says so literally?

      I saw some textbook examples that make the mixed uses of eval and do stuff in similar contexts. That is why I'm wondering.