仅当我在Windows上时,如何有条件地使用Perl模块? [英] How do I conditionally use a Perl module only if I'm on Windows?

查看:50
本文介绍了仅当我在Windows上时,如何有条件地使用Perl模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Perl代码..

The following Perl code ..

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

..在Windows上可以运行,但是不能在所有其他平台上运行(在@INC中找不到Win32.pm").如何指示Perl仅在Windows下运行时才尝试导入Win32,而在所有其他平台下忽略import语句?

.. works under Windows, but fails to run under all other platforms ("Can't locate Win32.pm in @INC"). How do I instruct Perl to try import Win32 only when running under Windows, and ignore the import statement under all other platform?

推荐答案

此代码将在所有情况下均有效,并且还将在编译时执行加载,因为您正在构建的其他模块可能依赖于此:

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"
    }
}

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

(几年后,编辑...)

(EDIT, a few years later...)

这甚至更好:

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

此处了解更多有关if杂注的信息.

Read more about the if pragma here.

这篇关于仅当我在Windows上时,如何有条件地使用Perl模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆