How do you use a variable in lib Path?

2019-04-04 18:21发布

I would like to use the $var variable in lib path.

my $var = "/home/usr/bibfile;"

use lib "$var/lib/";

However when I do this it throws an error.

I'd like to use use lib "$var/lib/";instead of use lib "/home/usr/bibfile/lib/";.

How can I assign a variable, so that it can be used in the setting of lib modules?

3条回答
老娘就宠你
2楼-- · 2019-04-04 18:56

Not sure about what you're trying to accomplish, but seems like a task for FindBin::libs:

my $var;
BEGIN { $var = "/home/usr/bibfile" };
use FindBin::libs "Bin=$var", "base=lib";
查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-04 19:04

First, you have a simple syntax error - you're missing ; after first line. my variable should otherwise work fine in use lib.

However, since all use directives are executed in BEGIN block, your variable will be uninitialized at the moment you run use, so you need to put initialization in BEGIN block too.

my $var;
BEGIN { $var = "/home/usr/bibfile"; }
use lib "$var/lib/";

use Data::Dumper;
print Dumper \@INC;

Gives:

$VAR1 = [
      '/home/usr/bibfile/lib/',
      # ... more ...
    ];
查看更多
萌系小妹纸
4楼-- · 2019-04-04 19:09

You can't, because the use directive is evaluated at compile time, while other variables are evaluated at runtime.

If your lib is located somewhere relative to your original script, you can use the standard module FindBin:

# $Bin from FindBin is the directory of the original script
use FindBin;
use lib "$FindBin::Bin/path/to/bib";
use MyModule;
查看更多
登录 后发表回答