Perl最后将Hash添加到Hash of Hash中

时间:2012-04-05 20:24:48

标签: perl hash structure hash-of-hashes perl5

我正在尝试将散列添加到我的散列哈希像这样:

  %funkce = (
    "funkce1" => {
      "file" => "soubor1",
      "name" => "jmeno1",
      "varargs" => "args",
      "rettype" => "navrat",
      "params" => [
                "typ",
                "typ2"
            ]
    },
    "funkce2" => {
      "file" => "soubor2",
      "name" => "jmeno2",
      "varargs" => "args",
      "rettype" => "navrat",
      "params" => [
          "typ",
          "typ2"
      ]
    }
  );
  $delka = keys %funkce;
  $funkce{ "funkce" . ($delka + 1)} = {
      "file" => "soubor3",
      "name" => "jmeno3",
      "varargs" => "args",
      "rettype" => "navrat",
      "params" => [
          "typ",
          "typ2"
        ]
    };

但是有一个问题。最后一个哈希是在%函数中添加为第一个但我希望它作为最后一个。我该如何解决?我做得对吗?感谢

2 个答案:

答案 0 :(得分:1)

哈希不保证插入顺序。你要求它哈希你的密钥,所以x > y <=/=> f(x) > f(y)

如果您想保证插入顺序,虽然我认为没有理由引入(tie)的开销,但标准方法是使用Tie::IxHash

列表结束,而不是哈希。哈希是从一组名称或ID到一组对象或值的数学映射。如果我们想到狗的名字然后,尽管我们可以按字母顺序排列狗的名字,但实际上没有“第一只狗”。

根据你的节目,

push( @funkce
    , { "file"    => "soubor1"
      , "name"    => "jmeno1"
      , "varargs" => "args"
      , "rettype" => "navrat"
      , "params"  => [ qw<typ typ2> ]
      });

同样有效。在$funkce{'funcke2'} 上输入$funkce[2]而不是$funkce{ '$funkce' . $i }$funkce[$i]几乎没有什么好处 如果您要增加其他名称,那么您应该以这种方式进行划分:$funkce{'funkce'}[2] // $funkce{'superfunkce'}[2]

对数字的名称和数组的离散部分使用散列是编程数据的好方法。 $funkce{'funkce'}[2]就像$funkce{'funkce2'}一样是一个单一的实体。

答案 1 :(得分:0)

如果您需要订购商品,请使用数组,如果您想要命名(无序)商品,请使用散列。要获得接近有序哈希的内容,您需要嵌套数组/哈希值或对哈希值进行排序或使用一些绑定类。

<强>嵌套

 @funkce = (
    { name => "funkce1",
      "file" => "soubor1",
      "name" => "jmeno1",
      "varargs" => "args",
      "rettype" => "navrat",
      "params" => [
                "typ",
                "typ2"
            ]
    },
    { name => "funkce2",
      "file" => "soubor2",
      "name" => "jmeno2",
      "varargs" => "args",
      "rettype" => "navrat",
      "params" => [
          "typ",
          "typ2"
      ]
    }
  );
 push @funkce, {
  name => "funkce3",
  "file" => "soubor3",
  "name" => "jmeno3",
  "varargs" => "args",
  "rettype" => "navrat",
  "params" => [
      "typ",
      "typ2"
    ]
};

<强>分拣

%funkce = ( ... ); # as in OP

# when using
foreach my $item (sort keys %funkce) {
  # do something with $funkce{$item}
}

<强>绑

Tie::IxHash但正如Axeman所说,你可能不需要/想要这个。