【发布时间】:2010-12-14 18:05:42
【问题描述】:
我对 Perl 构造函数中发生的事情有点困惑。我找到了这两个例子perldoc perlbot。
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";
我已经将我一直遇到的问题/困惑作为 cmets 注入到代码中。
【问题讨论】:
-
这是基本的 Perl 将列表转换为哈希。它交替进行,将第一个作为键,第二个作为值。 DWIM(按照我的意思去做)是 Perl 努力实现的目标——而且通常会达到。
-
因为这个页面对于“命名参数”(以及其他东西)这个话题非常有用,所以我在标题中添加了这个短语,以便人们可以找到它。
标签: perl constructor oop instance-variables