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

前端之家收集整理的这篇文章主要介绍了你如何正确处理数组中的哈希?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一系列哈希:

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";
}

给我

Use of uninitialized value in concatenation (.) or string at
convert.pl line 44.

错误来自哪里?

解决方法

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",$answer) = each %answers) {
    say "Question: $question";
    say "Answer: $answer";
}

输出

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

猜你在找的Perl相关文章