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

17,127

Solution 1

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 .

Solution 2

This is sort of like the differences between my, our, and local. The differences are important, but you should be using my 99% of the time.

Perl is a fairly old and crufty language. It has evolved over the years from a combination awk/shell/kitchen sink language into a stronger typed and more powerful language.

Back in Perl 3.x days before the concept of modules and packages solidified, there was no concept of modules having their own namespace for functions and variables. Everything was available everywhere. There was nothing to import. The use keyword didn't exist. You always used require.

By the time Perl 5 came out, modules had their own storage for variable and subroutine names. Thus, I could use $total in my program, and my Foo::Bar module could also use $total because my $total was really $main::total and their $total was really $Foo::Bar::total.

Exporting was a way to make variables and subroutines from a module available to your main program. That way, you can say copy( $file, $tofile); instead of File::Copy::copy( $file, $tofile );.

The use keyword simply automated stuff for you. Plus, use ran at compile time before your program was executed. This allows modules to use prototyping, so you can say foo( @array ) instead of foo( \@array ) or munge $file; instead of munge( $file );

As it says in the use perldoc's page:

It [use] is exactly equivalent to:
BEGIN { require Module; Module->import( LIST ); }

Basically, you should be using use over require 99% of the time.

I can only think of one occasion where you need to use require over use, but that's only to emulate use. There are times when a module is optional. If Foo::Bar is available, I may use it, but if it's not, I won't. It would be nice if I could check whether Foo::Bar is available.

Let's try this:

eval { use Foo::Bar; };
  my $foo_bar_is_available = 1 unless ($@);

If Foo::Bar isn't available, I get this:

Can't locate Foo/Bar.pm in @INC (@INC contains:....)

That's because use happens BEFORE I can run eval on it. However, I know how to emulate use with require:

BEGIN {
    eval { require Foo::Bar; Foo::Bar->import( qw(foo bar barfu) ); };
    our foo_bar_module_available = 1 unless ($@);
}

This does work. I can now check for this in my code:

our $foo_bar_module_available;
if ( $foo_bar_module_available ) {
    fubar( $var, $var2 );   #I can use it
}
else {
    ...                     #Do something else
}

Solution 3

Difference between use and require:

  • If we use "use" no need to give file extension. Ex: use server_update_file.
  • If we use "require" need to give file extension. Ex: require "server_update_file.pm";
  • "use" method is used only for modules.
  • "require" method is used for both libraries and modules.

Refer the link for more information: http://www.perlmonks.org/?node_id=412860

Share:
17,127

Related videos on Youtube

Sumit
Author by

Sumit

Updated on September 14, 2022

Comments

  • Sumit
    Sumit over 1 year

    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.

    • devnull
      devnull over 10 years
    • devnull
      devnull over 10 years
    • simbabque
      simbabque over 10 years
      In 5, it does not load these, it imports them into the current namespace, so you can say foo('stuff') and bar($var). If there also is a sub asdf in Module, you can still call that by saying Module::asdf($whatever).
    • ikegami
      ikegami over 10 years
      use Module qw(foo bar) # it will load foo and bar only is wrong. It will load (execute) the whole .pm just as if you had done use Module;. Assuming the module has a standard import, the difference is that the first does *caller::sub = \⊂ for foo and bar, and the later does it for everything in @EXPORT.
  • Sumit
    Sumit over 10 years
    One question : BEGIN { use Cwd; our $directory = cwd; } use lib $directory; # will it parse the BEGIN block first? If it is so then it means BEGIN block parsing starts before compiling code?
  • Lawrence Hutton
    Lawrence Hutton over 10 years
    @Nitesh: use and BEGIN blocks are processed in the order they're encountered. e.g., use First; BEGIN { say "Second" }; use Third; will require and import from First, then print "Second", then require and import from Third. (This is because use is little more than a hidden BEGIN block.)
  • Lawrence Hutton
    Lawrence Hutton over 10 years
    Aside from optional modules, the other major use for require is to handle modules which are very slow to load, but not always actually needed, so that you can wait until you know whether you need it or not before you take the time to load it.
  • David W.
    David W. over 10 years
    Good point. However, I started programming on a computer that ran on a 8085A chip at 1.5Mz with 48K of memory. (And this was a multi-user system!). To me, the definition of slow is a bit different than for you young whippersnappers. To me, slow means I can go out and get a cup of coffee while waiting for the program to finish. And, going out for a cup of coffee means flying on a plane to Italy and getting a nice espresso at a local cafe, then maybe do some sight seeing before coming back.
  • Jacob
    Jacob over 10 years
    Actually use Scalar::Util 1.0 qw(weaken) is more like BEGIN{ require Scalar::Util; Scalar::Util->VERSION(1.0); Scalar::Util->import(qw(weaken))} We should really update the docs.