你可以加載模塊的same way是File::Spec確實包括不同的模塊。
(假設use warnings;
,use strict;
和版本的聲明緊隨所有package
聲明在本崗位)
package Common::Copy::Win32;
sub do_this {}
package Common::Copy::Linux;
sub do_this {}
package Common::Copy;
my %module = (
MSWin32 => 'Win32',
linux => 'Linux',
);
my $module = $module{$^O} || 'Linux';
require "Common/Copy/$module.pm";
our @ISA = ("Common::Copy::$module");
#!/bin/perl
use Common::Copy;
Common::Copy->do_this();
這將要求子程序寫入方法可能不是你想要的。
它看起來像你真正想讓它export在similar way到File::Spec::Functions怎麼做。
該實現假定子程序不寫爲方法。
package Common::Copy;
require Exporter;
our @ISA = qw'Exporter'; # use Exporters `import` method
our @EXPORT = qw'do_this';
our @EXPORT_OK = qw'';
our %EXPORT_TAGS = (ALL => [ @EXPORT_OK, @EXPORT ]);
my %module = (
MSWin32 => 'Win32',
linux => 'Linux',
);
our $module = $module{$^O} || 'Linux';
require "Common/Copy/$module.pm";
$module = "Common::Copy::$module"; # full name of actual module
foreach my $subname (@EXPORT, @EXPORT_OK) {
my $subref = $module->can($meth); # misuses method lookup
no strict 'refs';
# import the subroutines into this namespace
# assumes they aren't written as methods
*{$subname} = \&$subref;
}
#!/bin/perl
use Common::Copy;
# use Common::Copy qw':all';
# use Common::Copy qw'do_this';
do_this();
可以使用[BEGIN塊以有條件地包括模塊在啓動時(http://perldoc.perl.org/functions/use.html),或[有條件地包括和參考模塊在運行時](http://stackoverflow.com/questions/1917261/how-can-i-dynamically-include-perl-modules-without-using-eval)。剩下的就是[按平臺分支](http://stackoverflow.com/questions/334686/how-can-i-detect-the-operating-system-in-perl)。爲了理智,我強烈建議提供一個單獨的公共接口作爲抽象層。 – rutter
[只有當我在Windows上時,如何有條件地使用Perl模塊?](http:// stackoverflow。com/questions/1441689/how-do-i-condition-use-a-perl-module-only-if-im-on-windows) – mob
@mob其實它不是重複的,因爲Kamikaze試圖加載其中一個幾個模塊,而不是有條件的。 –