【问题标题】:How do I conditionally use a Perl module only if I'm on Windows?仅当我在 Windows 上时,如何有条件地使用 Perl 模块?
【发布时间】:2009-09-17 22:43:28
【问题描述】:

下面的 Perl 代码..

if ($^O eq "MSWin32") {
  use Win32;                                                                                                                                                                                           
  .. do windows specific stuff ..
}

.. 在 Windows 下工作,但无法在所有其他平台下运行(“无法在 @INC 中找到 Win32.pm”)。如何指示 Perl 只在 Windows 下运行时尝试 import Win32,而在所有其他平台下忽略 import 语句?

【问题讨论】:

标签: perl module


【解决方案1】:

此代码适用于所有情况,并在编译时执行加载,因为您正在构建的其他模块可能依赖于它:

BEGIN {
    if ($^O eq "MSWin32")
    {
        require Module;
        Module->import();  # assuming you would not be passing arguments to "use Module"
    }
}

这是因为use Module (qw(foo bar)) 等同于BEGIN { require Module; Module->import( qw(foo bar) ); },如perldoc -f use 中所述。

(编辑,几年后...)

这样更好:

use if $^O eq "MSWin32", Module;

阅读有关if 编译指示here 的更多信息。

【讨论】:

  • Bareword "Module" not allowed while "strict subs" in use ... - 从远处看很好......
  • @jww 您应该用您要加载的实际模块名称替换“模块”。并且该命名空间需要在文件中使用package 语句声明。
  • 哦,知道了,谢谢。为什么不使用Win32? (我不是经验丰富的 Perl 老手,所以我经常需要查找基本的 Perl)。
【解决方案2】:

作为序列的快捷方式:

BEGIN {
    if ($^O eq "MSWin32")
    {
        require Win32;
        Win32::->import();  # or ...->import( your-args ); if you passed import arguments to use Win32
    }
}

你可以使用 if 编译指示:

use if $^O eq "MSWin32", "Win32";  # or ..."Win32", your-args;

【讨论】:

    【解决方案3】:

    一般来说,use Moduleuse Module LIST 在编译时评估,无论它们出现在代码中的什么位置。运行时等价物是

    require Module;
    Module->import(LIST)
    

    【讨论】:

      【解决方案4】:

      require Module;

      但是use 也调用importrequire 没有。因此,如果模块导出到默认命名空间,您还应该调用

      import Module qw(stuff_to_import);

      你也可以eval "use Module" - 如果 perl 可以在运行时找到正确的路径,效果很好。

      【讨论】:

      • 不要使用间接方法调用,它们远非最佳实践。请改用Module->import(qw(stuff));
      猜你喜欢
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2020-08-14
      • 2018-04-12
      • 1970-01-01
      相关资源
      最近更新 更多