Search code examples
perlrequireperl-module

Why LWP::UserAgent is imported by require LWP::UserAgent instead of use LWP::UserAgent?


I'm pretty new to this language but I've been using use to import a specific module before,

why LWP::UserAgent uses require to do the job as from perldoc LWP::UserAgent:

require LWP::UserAgent;

Solution

  • use LWP::UserAgent;
    

    is the same as

    BEGIN {
        require LWP::UserAgent;
        import LWP::UserAgent;
    }
    

    If require LWP::UserAgent; is acceptable, that goes to show that import does nothing for LWP::UserAgent. Maybe the point of the documentation's use of require is to subtly imply this?

    The only difference between require LWP::UserAgent; and use LWP::UserAgent; is thus when require is executed. For the former, it happens after the entire file has been compiled. For the latter, it occurs as soon as that statement has been compiled. In practical terms, there's no much difference for object-oriented modules.

    Personally, I use

    use LWP::UserAgent qw( );
    

    That's the same as

    BEGIN {
        require LWP::UserAgent;
    }
    

    That way, I'm guaranteed not to import anything I don't want, and I use the familiar use I use for other modules.