10

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sumit
  • 1,953
  • 6
  • 32
  • 58
  • 1
    http://stackoverflow.com/questions/2180554/in-perl-is-it-better-to-use-a-module-than-to-require-a-file – devnull Aug 14 '13 at 12:15
  • http://stackoverflow.com/questions/1161624/in-perl-what-is-the-difference-between-use-and-require-for-loading-a-module – devnull Aug 14 '13 at 12:15
  • 3
    http://learn.perl.org/faq/perlfaq8.html#Whats-the-difference-between-require-and-use- – devnull Aug 14 '13 at 12:16
  • 2
    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)`. – simbabque Aug 14 '13 at 12:29
  • `perldoc -f use`, `perldoc -f require` – Andy Lester Aug 14 '13 at 12:36
  • 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? – Sumit Aug 14 '13 at 12:41
  • 3
    `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`. – ikegami Aug 14 '13 at 13:44

3 Answers3

9

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
}
David W.
  • 105,218
  • 39
  • 216
  • 337
  • 1
    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. – Dave Sherohman Aug 14 '13 at 15:32
  • 4
    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. – David W. Aug 14 '13 at 15:54
  • 2
    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. – Brad Gilbert Aug 14 '13 at 19:09
6

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 .

aleroot
  • 71,077
  • 30
  • 176
  • 213
  • 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? – Sumit Aug 14 '13 at 12:39
  • 1
    @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.) – Dave Sherohman Aug 14 '13 at 15:27
1

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