简体   繁体   English

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

[英]How do I conditionally use a Perl module only if I'm on Windows?

The following Perl code .. 以下Perl代码..

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

.. works under Windows, but fails to run under all other platforms ("Can't locate Win32.pm in @INC"). ..在Windows下运行,但无法在所有其他平台下运行(“无法在@INC中找到Win32.pm”)。 How do I instruct Perl to try import Win32 only when running under Windows, and ignore the import statement under all other platform? 如何在Windows下运行时指示Perl尝试导入Win32,并忽略所有其他平台下的import语句?

This code will work in all situations, and also performs the load at compile-time, as other modules you are building might depend on it: 此代码适用于所有情况,并且还在编译时执行加载,因为您构建的其他模块可能依赖于它:

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

This is because use Module (qw(foo bar)) is equivalent to BEGIN { require Module; Module->import( qw(foo bar) ); } 这是因为use Module (qw(foo bar))相当于BEGIN { require Module; Module->import( qw(foo bar) ); } BEGIN { require Module; Module->import( qw(foo bar) ); } BEGIN { require Module; Module->import( qw(foo bar) ); } as described in perldoc -f use . BEGIN { require Module; Module->import( qw(foo bar) ); }perldoc -f中所述。

(EDIT, a few years later...) (编辑,几年后......)

This is even better though: 这甚至更好:

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

Read more about the if pragma here . 在这里阅读更多关于if pragma的信息

As a shortcut for the sequence: 作为序列的快捷方式:

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

you can use the if pragma: 你可以使用if pragma:

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

In general, use Module or use Module LIST are evaluated at compile time no matter where they appear in the code. 通常, use Moduleuse Module LIST在编译时进行评估,无论它们出现在代码中的哪个位置。 The runtime equivalent is 运行时等价物是

require Module;
Module->import(LIST)

require Module;

But use also calls import , require does not. 但是use也调用importrequire则没有。 So, if the module exports to the default namespace, you should also call 因此,如果模块导出到默认命名空间,您也应该调用

import Module qw(stuff_to_import) ; import Module qw(stuff_to_import) ;

You can also eval "use Module" - which works great IF perl can find the proper path at runtime. 您还可以eval "use Module" - 这非常eval "use Module" ,因为perl可以在运行时找到正确的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM