加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 06:28:07 所属栏目:大数据 来源:网络整理
导读:我有一系列哈希: my @questions = ( {"Why do you study here?" = "bla"},{"What are your hobbies?" = "blabla"}); 我尝试循环它: foreach (@questions) { my $key = (keys $_)[0]; $content .= "section{$key}nn$_{$key}nn";} 给我 Use of uniniti
我有一系列哈希:

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

我尝试循环它:

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

给我

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读