Search code examples
perlpackageperl-module

Global usage of tool location while using packages


I have a folder tmp which lies in the tool-directory and contains different modules like e.g. myModul.pm:

package myModul;

print "path in myModul.pm: $dirName\n";

Those are called in the Main, which looks the following:

#!/usr/bin/perl
use strict;
use warnings;
use File::Basename;
use Data::Dumper;

use vars qw($dirName);
BEGIN{
        $dirName = dirname(__FILE__);
        print "tool location: $dirName\n";
#        push @INC, "$dirName/tmp";
}

use lib "$dirName/tmp";

use myModul;
print Dumper \@INC;

The path dirName isn't been printed correctly in myModul.pm which is my problem. If I remove the package myModul line it works, but this isn't really a way to handle it.

I simply want to use the location of the Perl-script without hardcoding it...

I read topics like that and that and that but can't really figure out how this works. What I don't want is the need to manually set an environment variable or the kind. That's just another source of problems.


Solution

  • What you are looking for I think is the FindBin module.

    It allows you to include things relative to your current location like so:

    use FindBin;
    use lib $FindBin::RealBin. "../mod_path";
    use myModul;
    

    (You should also turn on strict and warnings)