13

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?

Tim
  • 4,414
  • 4
  • 35
  • 49
Sourcecode
  • 305
  • 4
  • 13

3 Answers3

27

Variables work fine in use lib, well, just like they do in any string. However, since all use directives are executed in BEGIN block, your variable will be not yet initialized 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 ...
    ];
Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
1

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";
creaktive
  • 5,193
  • 2
  • 18
  • 32
  • I 'd like to use `use lib "$var/lib/";` insted of `use lib "/home/usr/bibfile/lib/";` . How can I assign a variable, so that it can be use in the setting of lib modules. – Sourcecode Dec 19 '12 at 11:03
  • OK, edited the answer to suit your specific need :) However, I'd suggest you to avoid using hardcoded absolute paths and use ones relative to your current script (that is the purpose of FindBin::libs) – creaktive Dec 19 '12 at 11:08
  • 1
    @creaktive Your answer now suffers from the same error as the questioner encountered to start with. You can fix this using the solution in the accepted answer. – MattLBeck Dec 19 '12 at 12:04
-2

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;
mpe
  • 1,000
  • 1
  • 8
  • 25