2

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.

Community
  • 1
  • 1
EverythingRightPlace
  • 1,197
  • 12
  • 33

2 Answers2

3

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)

Sobrique
  • 52,974
  • 7
  • 60
  • 101
  • Why would you expect it to be? A module is a separate name space, so doesn't automatically include variables from your program. (that could get very messy) – Sobrique Jul 06 '15 at 13:50
  • But dirName is a global variable and of course I need it to be accessible from everywhere. – EverythingRightPlace Jul 06 '15 at 13:58
  • I'm afraid you may be misunderstanding the point and purpose of modules. Global variables aren't good or useful. Much of programming over the last 20 years has been about _limiting_ scope, not expanding it. – Sobrique Jul 06 '15 at 14:29
  • I am a beginner so you will most likely be right. You would suggest to use something like `$FindBin::Bin` in general in modules when I need the path of my tool? – EverythingRightPlace Jul 06 '15 at 14:36
  • The key question would be - what do you need this for? _usually_ what you get from modules is a bunch of generic-ish subroutines that you 'drive' from your main code. Thus any paths etc. _shouldn't_ be hardcoded into the module. – Sobrique Jul 06 '15 at 14:38
0

To access a variable in another package, you need to include the package in the mention.

$main::dirName
ikegami
  • 367,544
  • 15
  • 269
  • 518