How do you use a variable in lib Path?

Sourcecode picture Sourcecode · Dec 19, 2012 · Viewed 7.3k times · Source

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?

Answer

Oleg V. Volkov picture Oleg V. Volkov · Dec 19, 2012

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 ...
    ];