如果我在Windows上,如何有条件地使用Perl模块?

时间:2009-09-17 22:43:29

标签: perl module

以下Perl代码..

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

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

4 个答案:

答案 0 :(得分:21)

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

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

这是因为use Module (qw(foo bar))相当于perldoc -f use中描述的BEGIN { require Module; Module->import( qw(foo bar) ); }

(编辑,几年后......)

这甚至更好:

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

详细了解if pragma here

答案 1 :(得分:11)

作为序列的快捷方式:

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

你可以使用if pragma:

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

答案 2 :(得分:3)

通常,use Moduleuse Module LIST在编译时进行评估,无论它们出现在代码中的哪个位置。运行时等价物是

require Module;
Module->import(LIST)

答案 3 :(得分:1)

require Module;

use也会调用importrequire则不会。因此,如果模块导出到默认命名空间,您还应该调用

import Module qw(stuff_to_import);

你也可以eval "use Module" - 运行良好的IF perl可以在运行时找到正确的路径。