您可以像 File::Spec 那样加载 same way 的模块。
(假设 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();