[英]How to print an element from an array which is inside the hash in perl
我正在尝试从 API 打印多维格式的输出。
use strict;
use warnings;
use Data::Dumper;
my $content={
'school_set' => 'SSET1234',
'result' => [
{
'school_name' => 'school_abc',
'display_value' => 'IL25',
'school_link' => 'example.com',
'status' => 'registerd',
'status_message' => 'only arts',
'school_id' => '58c388d40596191f',
}
],
'school_table' => 'arts_schools'
};
print "school_name is=".$content{result}[0]{school_name};
print "school_status is=".$content{result}[3]{status};
output
Global symbol "%content" requires explicit package name (did you forget to declare "my %content"?) at test8.pl line 20.
Global symbol "%content" requires explicit package name (did you forget to declare "my %content"?) at test8.pl line 21.
我必须从结果中打印如下输出。
school_name = school_abc
school_status = registered
如果$content
是哈希引用,则需要先取消引用它。 为此使用箭头运算符:
$content->{result}[0]{school_name}
没有箭头的语法仅适用于%content
。
my %content = ( result => [ { school_name => 'abc' } ] );
print $content{result}[0]{school_name};
如果要打印所有结果,则必须以某种方式遍历数组。 例如
#!/usr/bin/perl
use warnings;
use strict;
my $content = {
'result' => [
{
'school_name' => 'school_abc',
'status' => 'registerd',
},
{
'school_name' => 'school_def',
'status' => 'pending',
}
],
};
for my $school (@{ $content->{result} }) {
print "school_name is $school->{school_name}, status is $school->{status}\n";
}
您的数据结构假定为一个数组,也许将循环输出用于感兴趣的数据会很有用。
数据以哈希引用的形式呈现,需要取消引用才能循环遍历数组。
以下代码片段基于您发布的代码,并演示了如何实现所需的输出。
use strict;
use warnings;
use feature 'say';
my $dataset = {
'school_set' => 'SSET1234',
'result' => [
{
'school_name' => 'school_abc',
'display_value' => 'IL25',
'school_link' => 'example.com',
'status' => 'registerd',
'status_message' => 'only arts',
'school_id' => '58c388d40596191f',
}
],
'school_table' => 'arts_schools'
};
for my $item ( @{$dataset->{result}} ) {
say "school_name is = $item->{school_name}\n"
. "school_status is = $item->{status}";
}
exit 0;
输出
school_name is = school_abc
school_status is = registerd
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.