skerr1 has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

Would someone please explain the differences between "use" and "require"? Start off simply and then go into as much detail as you can. I am looking for a simple direct explanation of the differences between the two. I've seen them used interchangeably, so I am confused.

Thanks for all your help!

Replies are listed 'Best First'.
(Ovid) Re: require and use
by Ovid (Cardinal) on Feb 12, 2002 at 20:34 UTC

    use happens at compile time (and calls the package's import method, if any) and require doesn't happen until run time.

    "use"ing a module will tell you at compile time if you have any compilation problems, but you won't find out with require until you actually hit the "require" statement while the code is running. use is more or less equivalent to the following:

    BEGIN { require Foo::Bar; Foo::Bar->import; }

    Typically, you want to use modules and not require them, but if you have a module that you don't want to load unless needed (perhaps in an error routine), then require it:

    sub error_handling { my $data = shift; require Data::Dumper; die Data::Dumper::Dumper $data; } # or sub error_handling { my $data = shift; require Data::Dumper; Data::Dumper->import; die Dumper $data; }

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: require and use
by impossiblerobot (Deacon) on Feb 12, 2002 at 20:17 UTC
    Type 'require use' in the search box at the top of the page, and you will find scads of answers to your questions. The official documentation is available in perlfunc.

    You might also try Super Search.

    Impossible Robot