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

Re: The 'eval "require $module; 1"' idiom

by davido (Archbishop)
on Apr 19, 2014 at 05:40 UTC ( #1082866=note: print w/replies, xml ) Need Help??

in reply to The 'eval "require $module; 1"' idiom

This is a generalized idiom, in the form of:

eval "something_that_might_fail(); 1;" or die "Message.";

In the general case, it makes sense because "something_that_might_fail()" could be some expression where "false" or "undef" are not out of band for success (ie, are perfectly valid return values even for a successful call).

In the specific case of "eval "require Some::Module; 1;" or die "Message.", your "Case 3" and "Case 3b" observations are accurate; require will return 1 on success. In this specific case, the 1; is redundant, though semantically it does maintain eval's return value to not be tied to the return value of the primary "thing that might fail."

On the one hand, one might say that "eval "require Foo; 1;" or die "Message";" is cargo culted. On the other hand, the idiom as a general tool is useful, and probably doesn't need to be optimized further just because this specific application doesn't need the 1;. It's healthy to decouple the thing that might fail's return value from the success sentinel, which is what the idiom does.

By the way; this is a very well researched question. Kudos.


Replies are listed 'Best First'.
Re^2: The 'eval "require $module; 1"' idiom
by sedusedan (Monk) on Apr 19, 2014 at 12:02 UTC

      I wish the supported lookaheads and lookbehinds, which would allow me to search a little more specifically for situations where the idiom is used outside of the "require" and "use" use case. If it did, I might try something like:

      if \(eval ["'](?!require|use).+?;\s*1;?["']


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1082866]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (8)
As of 2018-06-18 09:48 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (109 votes). Check out past polls.