Perl 变量使用的最佳实践
1. 包变量
在开发中,应避免使用普通的包变量。例如,不要使用包变量来存储模块内的状态。以下是一个使用包变量存储状态的示例:
package Customer;
use Perl6::Export::Attrs;
# State variables...
our %customer;
our %opt;
sub list_customers : Export {
for my $id (sort keys %customer) {
if ($opt{terse}) {
print "$customer{$id}{name}\n";
}
else {
print $customer{$id}->dump( );
}
}
return;
}
# and later in...
package main;
use Customer qw( list_customers );
$Customer::opt{terse} = 1;
list_customers( );
更好的选择是使用词法变量。如果需要在包外部访问这些变量,可以提供一个单独的子例程来实现:
package Customer;
use Perl6::Export::Attrs;
# State variables...
my %customer;
my %opt;
sub set_terse {
超级会员免费看
订阅专栏 解锁全文
19

被折叠的 条评论
为什么被折叠?



