仅当我在Windows上时,如何有条件地使用Perl模块? [英] How do I conditionally use a Perl module only if I'm on Windows?
问题描述
以下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屋!