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/perluse 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: blaQuestion: What are your hobbIEs?Answer: blabla
我发现这比哈希数组更容易使用,每个哈希只包含一个键/值对.
如果您想以某个(非排序)顺序遍历哈希,则有几个选项.简单的解决方案是按照您要访问它们的顺序维护一组键:
# In the order you want to access themmy @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: blablaQuestion: 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: blaQuestion: What are your hobbIEs?Answer: blabla总结
以上是内存溢出为你收集整理的你如何正确处理数组中的哈希?全部内容,希望文章能够帮你解决你如何正确处理数组中的哈希?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)