Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re^3: eval "require $class" seems wrong (--!$@)

by tye (Sage)
on Aug 22, 2007 at 19:05 UTC ( #634479=note: print w/replies, xml ) Need Help??

in reply to Re^2: eval "require $class" seems wrong
in thread eval "require $class" seems wrong

If you change "::" to "/" and append ".pm", then you don't need a string eval, you can just do require $class. I wouldn't even do eval { require $class } (non-string eval) unless I was wanting to work around the module not being found. But if you do want to eval, then the best choice is:

( my $file= $class ) =~ s-::|'-/-g; if( ! eval { require "$"; 1 } ) { # work-around the failure here }

But I don't find the argument against string eval compelling enough to have much of a strong preference between that and the below string eval unless there is risk that $class might contain mischevious data:

if( ! eval "require $class; 1" ) { # work-around the failure here }

If you don't want to work-around a failure (and trust $class), then the choices are:

eval "require $class; 1" or die $@;


( my $file= $class ) =~ s-::|'-/-g; require "$";

And I'd never use UNIVERSAL::require, since I consider poluting such a very global namespace to be way too much sin for the sake of saving one line of code.

- tye        

Replies are listed 'Best First'.
Re^4: eval "require $class" seems wrong (--!$@)
by ikegami (Pope) on Aug 22, 2007 at 19:14 UTC
    The 1 is useless since require always returns true. (If it encounters no error, it returns what the module returns. If the module returns false, it encountered an error. If it encounters an error, it throws an exception.)

      Yes, and the space is equally "useless" because require"$" works just fine. That doesn't mean I'm going to drop either of them.

      The "; 1" is part of the best practice. It may not change the effect of this particular code, but it means I don't have to worry about whether the preceeding code might return a false value rather than dieing. It also tells the reader that I'm testing whether eval succeeded not whether the eval'd code returned a true value (which also makes it clearer why I'm using eval at all).

      - tye        

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://634479]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2020-10-24 23:02 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (248 votes). Check out past polls.