我对Perl构造函数中发生了什么感到困惑。我发现这两个例子perldoc perlbot。面向对象的Perl构造函数语法
package Foo;
#In Perl, the constructor is just a subroutine called new.
sub new {
#I don't get what this line does at all, but I always see it. Do I need it?
my $type = shift;
#I'm turning the array of inputs into a hash, called parameters.
my %params = @_;
#I'm making a new hash called $self to store my instance variables?
my $self = {};
#I'm adding two values to the instance variables called "High" and "Low".
#But I'm not sure how $params{'High'} has any meaning, since it was an
#array, and I turned it into a hash.
$self->{'High'} = $params{'High'};
$self->{'Low'} = $params{'Low'};
#Even though I read the page on [bless][2], I still don't get what it does.
bless $self, $type;
}
而另一个例子是:
package Bar;
sub new {
my $type = shift;
#I still don't see how I can just turn an array into a hash and expect things
#to work out for me.
my %params = @_;
my $self = [];
#Exactly where did params{'Left'} and params{'Right'} come from?
$self->[0] = $params{'Left'};
$self->[1] = $params{'Right'};
#and again with the bless.
bless $self, $type;
}
这里是使用这些对象的脚本:我一直有
package main;
$a = Foo->new('High' => 42, 'Low' => 11);
print "High=$a->{'High'}\n";
print "Low=$a->{'Low'}\n";
$b = Bar->new('Left' => 78, 'Right' => 40);
print "Left=$b->[0]\n";
print "Right=$b->[1]\n";
我已经注射了问题/混乱作为评论进入代码。
这是基本的Perl将列表变成散列。它交替出现,以第一个为关键,第二个为价值。 DWIM(做我的意思)是Perl努力的目标 - 并且通常会命中。 – Axeman 2009-11-09 19:12:03