@EXPORT and @EXPORT_OK

@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;
}

总结:

  1. @EXPORT & @EXPORT_OK 输出subroutines or attributes 到当前上下文, 以便不用被实例化就能直接调用。
  2. @EXPORT_OK 为按需输出,需要 use XXX; 时以参数形式显示传入。
  3. 需要注意, use XXX; 时传入指定 list 意味着更改了默认 export list(@EXPORT)。也就是说,这个指定的 list 可以不用实例化直接调用(当然如果不在 @EXPORT & @EXPORT_OK ,直接调用还是会报错)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值