你如何正确处理数组中的哈希?

时间:2014-02-26 15:15:07

标签: perl

我有一系列哈希:

my @questions = (
    {"Why do you study here?" => "bla"},
    {"What are your hobbies?" => "blabla"});

我尝试循环播放它:

foreach (@questions) {
    my $key = (keys $_)[0];
    $content .= "\\section{$key}\n\n$_{$key}\n\n";
}

给我

  

在连接(。)或字符串中使用未初始化的值   convert.pl第44行。

错误来自哪里?

3 个答案:

答案 0 :(得分:3)

$_{$key}在哈希变量$key中查找%_。开头的sigil $表示结果的类型是标量。语法结构VAR{KEY}确定VAR必须是哈希。虽然$_%_使用相同的符号作为名称,但不同的符号会使它们成为无关的变量。

您需要将哈希引用$_取消引用到底层哈希中。其语法为$_->{$key}${$_}{$key}

有关该主题的更一般性介绍,请参阅reference tutorial

答案 1 :(得分:2)

@questions的元素是对哈希的引用,而不是哈希。因此,您应该像这样使用它们:

foreach (@questions) {
    my $key = (keys %$_)[0];
    print "\\section{$key}\n\n$_->{$key}\n\n";
}

有关如何创建和使用参考的信息,请参阅perlref

答案 2 :(得分:2)

Gilles already explained如何使用您当前的数据结构,但我建议您完全使用不同的数据结构:简单的哈希。

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my %answers = (
    "Why do you study here?" => "bla",
    "What are your hobbies?" => "blabla"
);

while (my ($question, $answer) = each %answers) {
    say "Question: $question";
    say "Answer: $answer";
}

输出:

Question: Why do you study here?
Answer: bla
Question: What are your hobbies?
Answer: blabla

我觉得这比哈希数组更容易使用,每个哈希只包含一个键/值对。

如果要以某个(非排序)顺序迭代哈希,有几个选项。简单的解决方案是按照您要访问它们的顺序维护一组键:

# In the order you want to access them
my @questions = ("What are your hobbies?", "Why do you study here?");

my %answers;
@answers{@questions} = ("blabla", "bla");

foreach my $question (@questions) {
    say "Question: $question";
    say "Answer: $answers{$question}";
}

输出:

Question: What are your hobbies?
Answer: blabla
Question: Why do you study here?
Answer: bla

另一种选择是使用Tie::IxHash(或更快的XS模块Tie::Hash::Indexed)来按插入顺序访问密钥:

use Tie::IxHash;

tie my %answers, "Tie::IxHash";

%answers = (
    "Why do you study here?" => "bla",
    "What are your hobbies?" => "blabla"
);

while (my ($question, $answer) = each %answers) {
    say "Question: $question";
    say "Answer: $answer";
}

输出:

Question: Why do you study here?
Answer: bla
Question: What are your hobbies?
Answer: blabla