【问题标题】:How do you treat hashes in arrays properly?如何正确处理数组中的哈希?
【发布时间】:2014-03-29 12:40:00
【问题描述】:

我有一个哈希数组:

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 行。

错误从何而来?

【问题讨论】:

    标签: perl


    【解决方案1】:

    $_{$key} 在散列变量%_ 中查找$key。开头的符号$ 表示结果的类型是标量。语法结构VAR{KEY} 决定VAR 必须是一个散列。尽管$_%_ 使用相同的符号作为名称,但不同的符号使它们成为不相关的变量。

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

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

    【讨论】:

      【解决方案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
      

      【讨论】:

      • +1 用于正确猜测我对结构的目标 - 即定义任意但固定的顺序 - 并提供解决方法。非常感谢。
      【解决方案3】:

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

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

      请参阅perlref 了解如何创建和使用引用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-30
        • 1970-01-01
        • 2015-06-04
        • 1970-01-01
        • 2018-06-18
        • 2014-01-04
        相关资源
        最近更新 更多