The difference between using Modulename; and use Modulename ();

Is there a difference between using Modulename; and use Modulename () ;? Sometimes I see, for example, the use of Carp; and sometimes use Carp ();

+6
source share
4 answers

As documented

use Modulename; 

basically coincides with

 BEGIN { require Modulename; import Modulename; } 

while

 use Modulename (); 

basically coincides with

 BEGIN { require Modulename; } 

This means that parens indicate that you do not want to import anything. (It would also prevent the pragma from doing his job.)


Carp exports confess , croak and carp by default, so

 use Carp; 

not suitable for

 use Carp qw( confess croak carp ); 

Using

 use Carp (); # or: use Carp qw( ); 

confess , croak and carp will not be added to the caller namespace. They will still be available through their full name.

 use Carp (); Carp::croak(...); 
+11
source

Without () , the import method of the package will be called, which may result in some default name numbers being exported to the namespace of the calling package.

Passing () explicitly says: "Do not import any names into my namespace."

Most modern object-oriented modules do not export anything by default, and there is nothing stopping them from manually polluting the namespace of callers if they want to, but specifying () is a signal that you are not relying on names. Magic appearance is only because you imported package.

+4
source

From the perlfunc documentation on use :

If you do not want to call the import package (for example, so that your namespace is not changed), the list is explicitly empty:

 use Module (); 

It is exactly equivalent

 BEGIN { require Module } 
+3
source

From perldoc -f use

If you do not want to call the package import method (for example, so that your namespace is not changed), the list is explicitly empty:

use Carp; imports several functions ( carp , etc.), but use Carp (); does not import any features.

+2
source

Source: https://habr.com/ru/post/945118/


All Articles