perl - 直接 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
解决方案
my %sentence1 = {
"due", 2,
"remit", 1
};
你做错了(你试图用一个键创建一个哈希,这是一个 hashref (不起作用)并且没有相应的值)。这就是为什么 perl 给你一个关于查找引用而不是偶数列表的警告。你自找的
my %sentence1 = (
"due", 2,
"remit", 1
);
推荐阅读
- javascript - Redux.js - 构建一个侦听器中间件来侦听调度的 thunk 操作
- android - 更新 support-v4 库
- azure - 自动/计划的每日 USQL 脚本执行
- mysql - 无法为 MySQL 设置密码
- sql - 数据库设计 - 跟踪用户提交数据的最新快照
- python - 无法根据字典中的项目获取值
- sql - 包含列的 SQL Server 索引 - 转换为 Oracle
- clr - 更改 machine.config 后 MMC 无法创建管理单元错误
- android - Android Studio 虚拟设备卡在 G 屏上
- go - Go Test 删除 logger.SetLogging 日志文件