What does

use Cwd qw(); 

mean in perl?

I know qw gives quotes to each elements inside ()But what about this case?

3

Best Answer


The qw() is a fancy way of writing an empty list. Doing () would be two characters shorter.

Passing an empty list to use is important to avoid importing. From the use documentation:

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

E.g. by default, the Cwd module exports getcwd. This doesn't happen if we give it the empty list:

use strict;use Cwd;print "I am here: ", getcwd, "\n";

works, but

use strict;use Cwd ();print "I am here: ", getcwd, "\n";

aborts compilation with Bareword "getcwd" not allowed while "strict subs" in use.

I believe that since qw() after use Module is for importing subroutines, when left empty it simply loads the module but doesn't import any subroutines into the namespace.

For example this throws an error since getcwd is not imported:

#!/usr/bin/perluse warnings;use strict;use Cwd qw();my $dir=getcwd;

But I'm not sure if this is the answer you was looking for..!

Usually it "imports" commands so you don't have to create an object and call the function on them.

Example (from perlmonks):

 #without qwuse CGI;my $q = CGI->new();my $x = $q->param('x');#with qwuse CGI qw/:standard/;my $x = param("x")

Source: http://www.perlmonks.org/?node_id=1701

Most modules have import groups like :all or :standard also.