我有这个Perl子程序:
sub ask_for_lease {
my $url = '/sp/api/v1/lease';
my $formdata = '{"classname":"lease",}';
my $c = REST::Client->new();
$c->setHost($wizhost);
$c->PUT (
$url
, $formdata
, $headers
);
my $r = from_json($c->responseContent());
#print Dumper($r);
#my @results = $r->{'results'};
my @items = %{@{$r->{'results'}}[0]}->{'items'};
print Dumper(@items);
for my $item (@items) {
print "=============\n";
print Dumper($item);
print "=============\n";
}
}
它产生这个输出:
$VAR1 = [
{
'owner' => undef,
'notes' => 'Simulation One',
'version' => undef,
'status' => 'Ready',
'name' => 'One',
'lease' => '7070',
'_oid' => '1'
},
{
'owner' => undef,
'notes' => 'Simulation Two',
'version' => undef,
'status' => 'Ready',
'name' => 'Two',
'lease' => '2',
'_oid' => '2'
},
{
'owner' => undef,
'notes' => 'Simulation Three',
'version' => undef,
'status' => 'Ready',
'name' => 'Three 2012',
'lease' => '3',
'_oid' => '3'
},
...
];
=============
$VAR1 = [
{
'owner' => undef,
'notes' => 'Simulation One',
'version' => undef,
'status' => 'Ready',
'name' => 'One',
'lease' => '7070',
'_oid' => '1'
},
{
'owner' => undef,
'notes' => 'Simulation Two',
'version' => undef,
'status' => 'Ready',
'name' => 'Two',
'lease' => '2',
'_oid' => '2'
},
{
'owner' => undef,
'notes' => 'Simulation Three',
'version' => undef,
'status' => 'Ready',
'name' => 'Three 2012',
'lease' => '3',
'_oid' => '3'
},
...
];
=============
我希望能够做的是迭代items
数组并打印status
和name
,但我不确定我是否取消引用{{1}正确的。
答案 0 :(得分:3)
该行
my @items = %{@{$r->{'results'}}[0]}->{'items'}
非常可疑。您正在提取$r->{results}
引用的数组的第一个元素,将其解除引用作为哈希,并在引用语法中使用该哈希。你应该有
Using a hash as a reference is deprecated
如果您有use strict
和use warnings
就位。
最好在图层中提取复杂的嵌套数据。在这种情况下,您可以将items
数组的引用转换为标量变量并使用它。
my $items= $r->{results}[0]{items};
for my $item ( @$items ) {
printf "name: %s, $item->{name};
printf "status: %s, $item->{status};
print "--\n";
}
如果您发布JSON数据,那么我们将能够提供更好的帮助