我们如何在 Perl 中为“use”命令使用变量?

Git*_*nth 3 perl

我正在尝试从用户那里获取输入并在我的运行中包含一些库。

“使用”后是否可以使用变量?

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

use $module;
Run Code Online (Sandbox Code Playgroud)

我收到以下错误。

./abc.pl 第 4 行的语法错误,靠近“use $module” 由于编译错误,./abc.pl 的执行中止。

cho*_*oba 6

这是不可能的,但您可以使用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});
Run Code Online (Sandbox Code Playgroud)

但是在类似情况下使用if更为常见。

use if $^O eq 'MSWin' => 'Win32::GUI';
Run Code Online (Sandbox Code Playgroud)