0

In perl, we import/use module we use Cwd; qw as representation of list/array.

But, I see in some code it's mentioned as below.

use Cwd qw(realpath cwd);
realpath( $0 ) =~ /(.+)\/[^\/]+$/;
require "$1/some_file.pl"

What does this mean ? Can you please help me to understand ?

StackGuru
  • 471
  • 1
  • 9
  • 25
  • 2
    The [documentation of `use`](https://perldoc.perl.org/functions/use.html) is a good starting point – Dada Sep 07 '20 at 06:06
  • `use MODULE LIST` loads the MODULE and imports its symbols given in LIST into the current package. So `use Cwd 'getcwd'` will import `getcwd` into the current package. If you did only do `use Cwd`, the symbol `getcwd` would not be directly available, and you would need to write `Cwd::getcwd()` to call the function – Håkon Hægland Sep 07 '20 at 06:38

1 Answers1

6

qw/STRING/ is the quote-word quote-like operator.

qw(realpath cwd)

is equivalent to

split(' ', q(realpath cwd))

and thus to

'realpath', 'cwd'

So,

use Cwd qw(realpath cwd);

is equivalent to

use Cwd 'realpath', 'cwd';

According to the documentation,

use Module LIST;

is equivalent to

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

so

use Cwd 'realpath', 'cwd';

is equivalent to

BEGIN {
   require Cwd;
   Cwd->import('realpath', 'cwd');
}

So what does import do? Well, that's entirely up to the module. It's common for modules to export the listed symbols into the caller's namespace. Cwd is no exception.

So, the following loads Cwd (if it's not already), and imports the functions realpath and cwd from it.

use Cwd qw(realpath cwd);

Finally,

$0, documented in perlvar, is the name of the script being executed.

realpath($0) is an absolute path to the script being executed, with symlinks resolved.

The regex match is used to extract everything up to the last /, i.e. the directory name in which the script is located.

Finally, require executes the specified file. (Although require is not the correct tool for this.)

A simpler version of your code:

use FindBin qw( $RealBin );
require("$RealBin/some_file.pl");
ikegami
  • 367,544
  • 15
  • 269
  • 518