在 perl book 的这个例子中,“_components”来自哪里?我知道添加 _ 来表示 sub 是包私有的,但这个似乎突然使用了领先分数。你能给我指出一些关于这个的来源吗?谢谢你。
package Computer;
@ISA = qw(StoreItem);
sub new {
my $pkg = shift;
my $obj = $pkg->SUPER::new("Computer", 0,0);
$obj->{_components} = [];
$obj->components(@_);
$obj;
}
sub components {
my $obj = shift;
@_ ? push (@{$ojb->{_components}}, @_) : @{$obj->{_components}};
}
sub price {
my $obj = shift;
my $price = 0;
my $component;
for my $component ($obj->components()) {
$price += $component->price();
}
$price;
}
Run Code Online (Sandbox Code Playgroud)
_components是哈希引用的文字键$obj。它不是“来自”任何地方。这是 Perl 语法的一个怪癖。在声明中
$obj->{_components} = [];
Run Code Online (Sandbox Code Playgroud)
$obj是对新创建的类实例的引用(在前面的语句中),并且_components被定义为该实例中的键,并被初始化为对空数组的引用。这相当于
$obj->{'_components'} = [];
Run Code Online (Sandbox Code Playgroud)
例如
$ perl -de0
Loading DB routines from perl5db.pl version 1.55
Editor support available.
Enter h or 'h h' for help, or 'man perldebug' for more help.
main::(-e:1): 0
DB<1> $obj->{a} = "hello";
DB<2> x $obj
0 HASH(0x800756bf8)
'a' => 'hello'
DB<3> p $obj->{'a'}
hello
DB<4> p $obj->{a}
hello
DB<5>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |