首页 > 解决方案 > 直接 perl 哈希引用和变成引用的哈希之间的区别

问题描述

我试图理解此处给出的代码示例:https ://www.perlmonks.org/?node_id=1083257以及示例中给出的直接创建的哈希引用与我首先作为哈希创建的引用之间的区别。当我运行以下代码时:

use strict;
use warnings;
use Algorithm::NaiveBayes;

my $positive = {
    remit => 2,
    due => 4,
    within => 1,
};
my $negative = {
    assigned => 3,
    secured => 1,
};

my $categorizer = Algorithm::NaiveBayes->new;
$categorizer->add_instance(
    attributes => $positive,
    label => 'positive');
$categorizer->add_instance(
    attributes => $negative,
    label => 'negative');

$categorizer->train;

my $sentence1 = {
    due => 2,
    remit => 1,
};

my $probability = $categorizer->predict(attributes => $sentence1);

print "Probability positive: $probability->{'positive'}\n";
print "Probability negative: $probability->{'negative'}\n";

我得到结果:

Probability positive: 0.999500937781821
Probability negative: 0.0315891654410057

但是,当我尝试通过以下方式创建哈希引用时:

my %sentence1 = {
    "due", 2,
    "remit", 1
};

my $probability = $categorizer->predict(attributes => \%sentence1);

我得到:

Reference found where even-sized list expected at simple_NaiveBayes.pl line 57.
Probability positive: 0.707106781186547
Probability negative: 0.707106781186547

为什么我的哈希与示例中给出的哈希引用\%sentence1不同?$sentence1

标签: perlhashnaivebayes

解决方案


my %sentence1 = {
    "due", 2,
    "remit", 1
};

你做错了(你试图用一个键创建一个哈希,这是一个 hashref (不起作用)并且没有相应的值)。这就是为什么 perl 给你一个关于查找引用而不是偶数列表的警告。你自找的

my %sentence1 = (
    "due", 2,
    "remit", 1
);

推荐阅读