我有一系列的哈希值:
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行的串联(。)或字符串中使用未初始化的值。
错误从何而来?
Gilles已经解释了如何使用当前数据结构,但是我建议您完全使用其他数据结构:简单的哈希。
#!/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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句