@EXPORT
Export subroutines, with no need to initialize an object when you use.
之前有提到过,以下两种方式等同:
use File::Basename;
## like
BEGIN { require File::Basename; File::Basename->import; }
其中的import没有传入list,并不意味着import nothing,而是将 @EXPORT 里所有的成员import到当前上下文。如果@EXPORT 不含有任何成员,等同于File::Basename->import; 未执行。
@EXPORT_OK
Export subroutines on demand basis, need qw() when use package.
以上两个全局 list 可同时使用,不过需要注意实际导入的list。 如 @EXPORT_OK = qw(multiply divide); 后直接调用add(), subtract 后syntax error。需要 qw (add subtract multiply divide)
##try_arithmetic.pl
use Arithmetic qw (multiply divide);
#print "1+1 = " . add(1,1) . "\n";
#print "1-1 = " . subtract(1, 1) . "\n";
print "2X2 = " . multiply(2, 2) . "\n";
print "4/2 = " . divide(4, 2) . "\n";
package Arithmetic;
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(add subtract);
@EXPORT_OK = qw(multiply divide);
sub add {
my ($no1,$no2) = @_;
my $result;
$result = $no1+$no2;
return $result;
}
sub subtract {
my ($no1,$no2) = @_;
my $result;
$result = $no1-$no2;
return $result;
}
sub multiply {
my ($no1,$no2) = @_;
my $result;
$result = $no1*$no2;
return $result;
}
sub divide {
my ($no1,$no2) = @_;
my $result;
$result = $no1/$no2;
return $result;
}
总结:
- @EXPORT & @EXPORT_OK 输出subroutines or attributes 到当前上下文, 以便不用被实例化就能直接调用。
- @EXPORT_OK 为按需输出,需要 use XXX; 时以参数形式显示传入。
- 需要注意, use XXX; 时传入指定 list 意味着更改了默认 export list(@EXPORT)。也就是说,这个指定的 list 可以不用实例化直接调用(当然如果不在 @EXPORT & @EXPORT_OK ,直接调用还是会报错)。