ado
ado

Reputation: 1471

Difference between use Modulename; and use Modulename();

Is there any difference between use Modulename; and use Modulename(); ? Sometimes I see, for example, use Carp; and sometimes use Carp ();

Upvotes: 6

Views: 171

Answers (4)

ikegami
ikegami

Reputation: 385496

As documented,

use Modulename;

is the basically the same as

BEGIN {
   require Modulename;
   import Modulename;
}

while

use Modulename ();

is the basically the same as

BEGIN { require Modulename; }

That means the parens specify that you don't want to import anything. (It would also prevent a pragma from doing its work.)


Carp exports confess, croak and carp by default, so

use Carp;

is short for

use Carp qw( confess croak carp );

By using

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

confess, croak and carp won't be added to the caller's namespace. They will still be available through their fully qualified name.

use Carp ();
Carp::croak(...);

Upvotes: 12

toolic
toolic

Reputation: 61937

From perldoc -f use

If you do not want to call the package's import method (for instance, to stop your namespace from being altered), explicitly supply the empty list:

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

Upvotes: 3

Mark Reed
Mark Reed

Reputation: 95242

Without the (), the package's import method will be called, possibly causing some default set of names to be exported into the calling package's namespace.

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

Most modern object-oriented modules don't export anything by default anyway, and there's nothing stopping them from manually polluting the caller's namespace if they wanted to, but specifying () is a signal that you're not relying on names magically appearing just because you imported a package.

Upvotes: 5

Greg Bacon
Greg Bacon

Reputation: 139411

From the perlfunc documentation on use:

If you do not want to call the package's import method (for instance, to stop your namespace from being altered), explicitly supply the empty list:

use Module ();

That is exactly equivalent to

BEGIN { require Module }

Upvotes: 4

Related Questions