我有一个创建文档对象的包:
package Document;
sub new
{
my ($class, $id) = @_;
my $self = {};
bless $self, $class;
$self = {
_id => $id,
_title => (),
_words => ()
};
bless $self, $class;
return $self;
}
sub pushWord{
my ($self, $word) = @_;
if(exists $self->{_words}{$word}){
$self->{_words}{$word}++;
}else{
$self->{_words}{$word} = 0;
}
}我称之为:
my @docs;
while(counter here){
my $doc = Document->new();
$doc->pushWord("qwe");
$doc->pushWord("asd");
push(@docs, $doc);
}在第一次迭代中,第一次$doc的哈希有两个元素,在第二次迭代时,第二次$doc的哈希有四个元素(从第一个迭代中抽取两个)。但是当我使用这个实体对象(创建一个Document数组)时,我得到:
为什么散列的大小在增加?Document-3包含Document-1和Document-2中的所有散列内容。这与加持或未定义变量有关吗?构造函数错了吗?
谢谢:D
发布于 2014-11-22 18:01:56
你有两个主要问题
$self初始化
$self ={ _id => $id,_title => (),_words => () };
这是非常错误的,因为空括号()没有向结构添加任何内容。如果我在这之后转储$self,我会得到
{ _id => 1,_title => "_words“}
您还为$self祝福了两次,但这并没有问题:这更多地表明您不明白自己在做什么。1,而不是0。下面是您的代码按应有方式工作的示例。我使用Data::Dump来显示这三个文档对象的内容。
use strict;
use warnings;
package Document;
sub new {
my ($class, $id) = @_;
my $self = {
_id => $id,
_words => {},
};
bless $self, $class;
}
sub pushWord {
my ($self, $word) = @_;
++$self->{_words}{$word};
}
package main;
use Data::Dump;
my $doc1 = Document->new(1);
my $doc2 = Document->new(2);
my $doc3 = Document->new(3);
$doc1->pushWord($_) for qw/ a b c /;
$doc2->pushWord($_) for qw/ d e f /;
$doc3->pushWord($_) for qw/ g h i /;
use Data::Dump;
dd $doc1;
dd $doc2;
dd $doc3;输出
bless({ _id => 1, _words => { a => 1, b => 1, c => 1 } }, "Document")
bless({ _id => 2, _words => { d => 1, e => 1, f => 1 } }, "Document")
bless({ _id => 3, _words => { g => 2, h => 2, i => 2 } }, "Document")https://stackoverflow.com/questions/27080307
复制相似问题