When should we use “use” and when “require” and when “AUTOLOAD” in perl ? I need a thumb rule for this.
When should we use use and when require and when AUTOLOAD in perl ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
useis equivalent toBEGIN { require Module; Module->import( LIST ); }So, the main difference is that:
Use is used at compile time
Use automatically calls import subroutine (which can do anything but mostly used to export identifiers into caller’s namespace)
use dies if the module can not be loaded (missing/compile error)
As such:
When you need to load modules dynamically (for example, determine which module to load based on command line arguments), use
require.In general, when you need to precisely control when a module is loaded, use
require(usewill load the module right after the precedinguseorBEGINblock, at compile time).When you need to somehow bypass calling module’s
import()subroutine, userequireWhen you need to do something smart as far as handling load errors (missing module, module can’t compile), you can wrap the
requireinto aneval { }statement, so the whole program doesn’t just die.You can simulate that with
usebut in rather in-elegant ways (trappingdiesignal in an earlyBEGINblock should work). Buteval { require }is better.In all OTHER cases, use
useI didn’t cover AUTOLOAD as that’s a different beastie. Its usage is in cases when you want to intercpt calls to subroutines that you haven’t imported into your namespace.