0

我正在尝试将哈希添加到我的哈希哈希中,如下所示:

  %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"
        ]
    };

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

4

2 回答 2

1

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

如果你想保证插入顺序,虽然我认为没有理由引入(a 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'}.

于 2012-04-05T20:29:38.803 回答
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 所说,你可能不需要/想要这个。

于 2012-04-05T20:52:35.097 回答