How can we use a variable for the "use" command in Perl?

Viewed 327

I'm trying to get the input from the user and include some libraries in my run.

Is is possible to use a variable after "use"?

$filepath = "abc/xyz.pm";
$module = "xyz";

use $module;

I get the following error.

syntax error at ./abc.pl line 4, near "use $module" Execution of ./abc.pl aborted due to compilation errors.

3 Answers

It's not possible, but you can work around it using require:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

BEGIN {
    my $module = 'JSON::XS';  # Used as an example
    my $path = $module =~ s{::}{/}gr . '.pm';
    require $path;
    $module->import();
}

say encode_json({a=>12});

It's more common to use if in similar situations, though.

use if $^O eq 'MSWin' => 'Win32::GUI';
use Package;

is (almost) equivalent to

require Package;
Package->import();

but executed during compilation.

If you do want to add "./abc" to the path where modules are located you can either

use lib 'abc';

or add the path to the @INC directory.

So your code could be:

unshift @INC, 'abc';
$module = "xyz";
require $module;
$module->import();

Assuming that the script you are going to invoke resides in some other path, you can include like below :

$filepath = "abc";
$module = "xyz.pm";

push(@INC, $filepath); #INC is like sys.path in python
require "$module"; #Use require to load modules in runtime
eval("$module\:\:$funtion_name()"); #Call the function from that module
Related