sedusedan has asked for the wisdom of the Perl Monks concerning the following question:
Could someone refresh me on why the ; 1 part is necessary again? In other words, why is this idiom safer/better/more correct than just eval "require $module", especially in the context of using the expression in conditional (e.g.: eval "require $module; 1" or warn "Can't load $module";). I've used this idiom for years, and recently even submitted a patch to Log::Log4perl related to this. But for the love of heaven, I forgot why it's needed in the first place. Let's consider the cases:
Case 1. Module cannot be not found on the filesystem. require dies with message "Can't locate $module in @INC ...", eval traps it and sets $@ and returns undef. ; 1 part in idiom is not needed (unreached).
Case 1b. Like case 1, but previous attempt has been made. Ditto.
Case 2. Module has compile errors. require dies with compile error message, eval traps it and sets $@ and returns undef. ; 1 part in idiom is not needed (unreached).
Case 2b. Like case 2, but previous attempt has been made. After the first attempt, the entry in %INC is set to undef. At the second attempt, require will die with message "Attempt to reload $module aborted", eval traps it, sets $@, and returns undef. ; 1 part in idiom is not needed (unreached).
Case 3. Module is loaded successfully and returns a true value (in other words, the normal success case). require will return 1. ; 1 part in idiom is not needed.
Case 3b. Like Case 3, but previous loading has been made. require will return 1. ; 1 part in idiom is not needed.
Case 4. Module is loaded successfully but returns a non-true value. require will die with message "$module did not return a true value ...". eval traps it, sets $@, and returns undef. ; 1 part in idiom is not needed (unreached).
Case 4b. Like case 4, but previous attempt has been made. Ditto.
There are other cases possible (like a permission error when reading source file, require() being overriden, etc) but the above are the common/majority cases. So what cases does the ; 1 part cover? Does this have something to do with older versions of perl (I'm testing this on 5.18.2).
|
---|