简体   繁体   English

数组哈希中的Perl访问元素

[英]Perl access elements in an array hash

I am trying to access elements of an array of hashes. 我正在尝试访问哈希数组的元素。

This is a dump of my variable $tst 这是我的变量$tst的转储

[
  { DESCRIPTION => "Default", ID => 0, NAME => "Default",  VERSION => "1.0" },
  { DESCRIPTION => "",        ID => 1, NAME => "Custom 1", VERSION => "1.1" },
  { DESCRIPTION => "",        ID => 2, NAME => "Custom 2", VERSION => "1.0" },
  { DESCRIPTION => "",        ID => 3, NAME => "Custom 3", VERSION => "6.0" },
  { DESCRIPTION => "",        ID => 4, NAME => "Custom 4", VERSION => "1.0" },
]

I am trying to access the values for the elements. 我正在尝试访问元素的值。 For example if the ID is 4 then return the field NAME . 例如,如果ID为4,则返回NAME字段。

I tried printing all of the values for ID but it hasn't been working. 我尝试打印ID所有值,但没有用。

I used variations of the Perl code below from looking online 从网上看,我使用了下面的Perl代码变体

foreach ($tst) {
  print "$_->{'ID'}, \n";
}

And it gives the following error: 并且它给出以下错误:

Not a HASH reference at file.pl line 22.

Note : line 22 is the print line from above. 注意 :第22行是上方的print行。

You first have to dereference the array of hash. 您首先必须取消引用哈希数组。 So, 所以,

foreach (@$tst) {
    print $_->{ID}, "\n";
}

should print all the IDs. 应该打印所有ID。

The answer that you have accepted is correct, but your data structure is such that you can index the array by the ID value. 您接受的答案是正确的,但是您的数据结构使您可以通过ID值对数组进行索引。 That is to say $tst->[$id]{ID} == $id for all elements. 也就是说,所有元素的$tst->[$id]{ID} == $id

So, to print the NAME field for the ID 4 you can say 因此,要打印ID 4的NAME字段,您可以说

print $tst->[4]{NAME}, "\n";

and you will see 你会看到

Custom 4

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM