Perl访问数组哈希中的元素

时间:2020-12-05 21:22:44

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行是上面的打印行。

2 个解决方案

#1


4  

You first have to dereference the array of hash. So,

首先必须取消引用哈希数组。所以,

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

should print all the IDs.

应该打印所有的ID。

#2


3  

The answer that you have accepted is correct, but your data structure is such that you can index the array by the ID value. That is to say $tst->[$id]{ID} == $id for all elements.

您接受的答案是正确的,但您的数据结构是可以通过ID值索引数组。也就是说所有元素的$ 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.

我希望这有帮助。

#1


4  

You first have to dereference the array of hash. So,

首先必须取消引用哈希数组。所以,

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

should print all the IDs.

应该打印所有的ID。

#2


3  

The answer that you have accepted is correct, but your data structure is such that you can index the array by the ID value. That is to say $tst->[$id]{ID} == $id for all elements.

您接受的答案是正确的,但您的数据结构是可以通过ID值索引数组。也就是说所有元素的$ 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.

我希望这有帮助。