【问题标题】:Perl OO - Creating a list of objectsPerl OO - 创建对象列表
【发布时间】:2014-11-22 17:30:00
【问题描述】:

我有一个创建 Document 对象的包:

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

  • 散列大小为 x 的 Document-1
  • 散列大小为 x+y 的 Document-2
  • 散列大小为 x+y+z 的 Document-3

为什么哈希的大小会增加? Document-3 包含 Document-1 和 Document-2 中的所有哈希内容。这与祝福或取消定义变量有关吗?构造函数错了吗?

谢谢:D

【问题讨论】:

  • “哈希大小”是什么意思?
  • 如果不清楚,抱歉。我的意思是哈希的总元素。所以 Document-2 的 hash 拥有 Document-1 的 hash 的所有元素。
  • 这不是我得到的行为。您的构造函数肯定是错误的,但请同时显示您的调用代码。
  • 编辑了我如何称呼它的简化。这个想法是我想计算每个文档中每个单词的频率。
  • 我无法复制问题。

标签: perl oop object hash


【解决方案1】:

你有两个主要问题

  • 您对$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")

【讨论】:

  • 解决了我的问题,还教我如何使用Data::Dump。感谢您回答像我这样的新手的问题:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
相关资源
最近更新 更多