Nitesh Nitesh - 2 days ago 4
Perl Question

Difference between use and require (I listed the differnces, need to know what else are there)

I read the explanation even from

perldoc
and
StackOverflow
. But there is a little confusion.


  1. use
    normally loads the module at compile time whereas
    require
    does at run time

  2. use
    calls the import function inbuilt only whereas
    require
    need to call import module separately like

    BEGIN {
    require ModuleName;
    ModuleName->import;
    }

  3. require
    is used if we want to load bigger modules occasionally.

  4. use
    throws the exception at earlier states whereas
    require
    does when I encounters the issue

  5. With
    use
    we can selectively load the procedures not all but few like

    use Module qw(foo bar) # it will load foo and bar only



is it possible in
require
also?

Beisdes that are there another differences between
use
and
require
?

Lot of discussion on google but I understood these above mentioned points only.

Please help me other points.

Answer

I think that the code you written by your own in the second point is self explanatory of the difference between the two ...

In practice "use" perform a "require" of the module and after that it automatically import the module, with "require" instead the module is only mandatory to be present but you have the freedom to import it when you need it ...

Given what stated above it result obvious that the question in the point 5 have no sense, since "require" doesn't import anything, there is no need to specify the module part to load, you can selectively load the part you need when you will do the import operation ...

Furthermore bear in mind that while "use" act at compile time(Perl compilation phase), "require" act at runtime, for this reason with "require" you will be able to import the package only if and/or when it is really needed .

Comments