1

I have to write scripts for a project. Since we have structured folders (in Linux environment) to be followed to put the scripts with respect to each modules which we create.

So, for example, I am working on Project XYZ and for this project I have to write my scripts (majority Perl) inside Module_XYZ. Path to all(common) the modules is /home/shared/Mining/.

My project module(Module_XYZ) goes inside /home/shared/Mining/. So I have to write scripts in /home/shared/Mining/Module_XYZ/

Since I have to use this path more often(in the script) instead of mentioning this path again and again I am storing in the script at the beginning in environment variable.

our %ENV;
if ( !defined( $ENV{'MOD_PATH'} ) ) {
    $ENV{'MOD_PATH'} = "/home/shared/Mining/Module_XYZ/";
}

Is it a good idea to add this path in ENV varaible and call $ENV{'MOD_PATH'} whenever required, or should I go with declaring it as constant like:

use constant MOD_PATH => "/home/shared/Mining/Module_XYZ/";

or simply go with

$MOD_PATH = "/home/shared/Mining/Module_XYZ/";

Need experts suggestions. TIA.

vkk05
  • 3,137
  • 11
  • 25
  • 1
    Take a look at https://stackoverflow.com/questions/84932/how-do-i-get-the-full-path-to-a-perl-script-that-is-executing – UjinT34 Aug 01 '20 at 12:31

1 Answers1

2

You're much better off not mentioning anything like /home/shared/Mining anywhere in your code base but rather using relative directories and running your script from the project folder. This will make the project more portable.

If your script (the .pl file) is importing .pm files in Module_XYZ then it should setup the @INC using use lib 'Module_XYZ' and the script should be run from the /home/shared/Mining directory, or wherever Module_XYZ is located.

If Module_XYZ contains some other files then again you should just refer to them relative to the currently running script's directory e.g (-f Module_XYZ/foo.txt).

Using constant or just my $MOD_PATH = "MODULE_XYZ" is a bit better than reading $ENV{MOD_PATH} because you'll get compilation errors if there's a typo or if $MOD_PATH isn't in scope or doesn't exist.

mekazu
  • 2,545
  • 3
  • 23
  • 21
  • 3
    `use lib 'Module_XYZ';` should be `use FindBin qw( $RealBin ); use lib $RealBin;` (or `"$RealBin/lib"`, etc). Relying on `.` being the script's directory is going to bite you – ikegami Aug 01 '20 at 14:31