Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why add LIST after a use statement?

Tags:

perl

What's the difference between say use File::Spec; and use File::Spec qw(rel2abs);?

Believe it or not, I did try googling this first, but I guess the words use and list are too vague for Google to find anything useful.

Just to be clear, my question is not about the use of qw(). I'm just asking about the list it contains.

like image 418
LongTP5 Avatar asked Mar 02 '23 06:03

LongTP5


1 Answers

use Module;

is equivalent to

BEGIN { 
   require Module;
   Module->import();
}

What import does is up to the module. It might do nothing, it might export symbols, or it might do something else. Many modules have a default list of symbols this exports.


use Module LIST;

is equivalent to

BEGIN { 
   require Module;
   Module->import(LIST);
}

What import does is up to the module. It might do nothing, it might export symbols, or it might do something else. Many modules will export the specified symbols (and no others).


use Module ( );

and

use Module qw( );

are equivalent to

BEGIN { 
   require Module;
}

import is not called.


File::Spec doesn't define or inherit an import method, so use File::Spec; and use File::Spec qw( rel2abs ); are equivalent to use File::Spec qw( );. (Invoking a non-existent import method doesn't result in an error.) use File::Spec qw( rel2abs ); was probably supposed to be use File::Spec::Functions qw( rel2abs );.


I almost never use Module;; I prefer to specify the symbols I want to import. This has two benefits:

  • I don't import symbols I don't need. Avoiding namespace pollution provides a few minor benefits that amount to "less chance of being surprised".
  • The people reading my code (incl myself) can easily find the module that provides an imported symbol.
like image 111
ikegami Avatar answered Mar 05 '23 14:03

ikegami