It's best to avoid eval STRING whenever possible since it forces runtime recompilation, and is thus rather slow.

Avoiding string eval is generally good advice. Always avoiding it just for speed reasons is premature micro optimization. If you were doing this in a loop and profiling showed that it was actually causing you a noticeable slow-down, then that would be a good reason to refactor the code to avoid it.

My taste leads me to prefer much simpler code that runs a few milliseconds slower nearly every time.

You left out the code to set what class to use when creating the object(s). If you add that in, then you are having to say each package name 3 times. I'd rather use the code I provided above. (:

Thanks for mentioning the fatal error trapping. In this situation, eval's trapping of errors is a disadvantage. I should have mentioned that the extra step would be required if the "simpler" eval "use $module" were used. I'd just die "$@\n" if $@; so that the error message is as expected.

Also note that you need to put the die code inside the BEGIN block in your code above.

                - tye

In reply to Re^4: using a variable to specify which perl module to use (bareword) by tye
in thread using a variable to specify which perl module to use by princepawn

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.