[英]How to get data from Perl data structure
I've parsed JSON into the following data structure:我已将 JSON 解析为以下数据结构:
$VAR1 = {
'041012020' => {
'item_number' => 'P2345'
},
'041012021' => {
'item_number' => 'I0965'
},
'041012022' => {
'item_number' => 'R2204'
}
};
I'm trying to get the values of item_numbers using the following code, and it's giving me the HASH Values as output rather than the actual item_number values.我正在尝试使用以下代码获取 item_numbers 的值,它给了我 HASH 值作为 output 而不是实际的 item_number 值。 Please guide me to get the expected values.请指导我获得预期值。
foreach my $value (values %{$json_obj}) {
say "Value is: $value,";
}
Output: Output:
Value is: HASH(0x557ce4e2f3c0),
Value is: HASH(0x557ce4e4de18),
Value is: HASH(0x557ce4e4dcf8),
If I use the same code to get the keys it's working perfectly fine如果我使用相同的代码来获取密钥,它工作得很好
foreach my $key (keys %{$json_obj}) {
say "Key is: $key,";
}
Output: Output:
Key is: 041012020,
Key is: 041012020,
Key is: 041012022,
The values of the hash elements are references to hashes ( { item_number => 'P2345' }
). hash 元素的值是对哈希的引用 ( { item_number => 'P2345' }
)。 That's what you get when you stringify a reference.这就是对引用进行字符串化时得到的结果。 If you want the item number, you'll need to tell Perl that.如果您想要商品编号,您需要告诉 Perl。
for my $value (values %$data) {
say $value->{item_number};
}
or或者
for my $item_number ( map { $_->{item_number} } values %$data ) {
say $item_number;
}
Here is the short code for your question.这是您问题的简短代码。
#!usr/bin/perl $VAR1 = { '041012020' => { 'item_number' => 'P2345' }, '041012021' => { 'item_number' => 'I0965' }, '041012022' => { 'item_number' => 'R2204' } }; print "$VAR1->{$_}->{item_number}\n" for keys %$VAR1;
To use for in a block:在块中使用:
for my $key (keys %$VAR1) {
print "$VAR1->{$key}->{item_number}\n"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.