2014-11-22 80 views
0

的名单我有一个创建一个文档对象包:的Perl OO - 创建对象

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数组),我得到:

  • 文献-1,其中x
  • 文献-2的散列大小与x的散列大小+ Y
  • 文档 - 3,散列大小为x + y + z

为什么散列大小递增? Document-3具有Document-1和Document-2中的所有散列内容。这是否与祝福或未定义变量有关?构造函数是否错误?

感谢:d

+0

你所说的 “散列大小” 是什么意思? – choroba 2014-11-22 17:36:43

+0

哦,对不起,如果它不明确。我的意思是散列的总元素。因此,Document-2的散列具有Document-1散列的所有元素。 – 2014-11-22 17:39:05

+0

这不是我得到的行为。你的构造函数肯定是错误的,但也请显示你的调用代码。 – Borodin 2014-11-22 17:46:16

回答

3

你有两个主要问题

  • 你的$self

    $self = { 
        _id => $id, 
        _title =>(), 
        _words =>() 
    }; 
    

    初始化是非常错误的,因为空括号()没有增加任何新的结构。如果我在此之后倾倒$self我得到

    { _id => 1, _title => "_words" } 
    

    你也祝福$self两次,但有没有问题:它更多的是一个指示,你不明白你在做什么。

  • 没有必要为首次出现的单词初始化散列元素:Perl会为您做这件事。另外,您应该将计数初始化为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") 
+1

它解决了我的问题,你也教我如何使用'Data :: Dump'。感谢您回答我这样的新手提出的问题:D – 2014-11-22 18:13:07