How do I use a Perl module from a relative location?

前端 未结 8 2196
予麋鹿
予麋鹿 2020-12-23 16:41

I have a dir called foo, and in that I have lib and bin. The scripts in bin need stuff in lib. I do someth

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-23 17:04

    The "FindBin" module will only work if the directory that the perl script resides in is in your system PATH, else it will fail. To overcome that you can manipulate the $0 value to get your path-to-perl-module information and pass the value to use lib.

    Something like this -

    BEGIN {
        use File::Spec::Functions qw(rel2abs);
        use File::Basename qw(dirname);
    
        #Covert the script path to absolute and get its directory name
        our $path = dirname( rel2abs($0) );
    
        #Replace the bin tag with lib to get module directory
        $path =~ s{bin/?$}{lib};
    }
    
    use lib $path;
    

    EDIT: The FindBin module works just perfectly and can be used as described in Michael's answer. My understanding of its workings was incomplete and so led me to making the first comment which I now retract. Anyway, I don't see any reason why this method shouldn't work albeit with a few more lines than could be achieved using FindBin (TMTOWTDI).

提交回复
热议问题