Performance questions such as these can be answered empirically by using Benchmark. The accompanying POD describes its use.

The theory behind the performance difference will involve the fact that the string that you're evaling must be compiled at runtime, which will take a little time. Whether or not the time it takes is significant to your script's performance is another question. More often than not, the answer is ...not really. But you would have to profile a time-critical script to determine where the bottlenecks are before digging into how to optimize speed performance.

Common uses for eval strings are varied. One is to build a regexp on the fly. Another is to bring back to life something that was previously dumped via Data::Dumper (though the eval is often done behind the scenes via the same module).

And of course, any time that you find you really don't know how the code is supposed to come together until runtime string eval comes in handy (the regexp-on-the-fly is just one example).

For the most part, you won't need string eval, except when you really need it, and in those cases, it will seem natural (though it can be tricky getting metacharacters and quoting right).

eval is also useful, of course, for trapping errors, though often that's done using the block version of eval rather than the string version.

There is a really good chapter on eval in Advanced Perl Programming, published by O'Reilly & Associates (known as the Cougar book). It gives a few great examples.


Dave


In reply to Re: eval string possibilities by davido
in thread eval string possibilities by erix

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.