Deano Deano - 7 months ago 21
Perl Question

Perl loop through hash

I'm trying to parse an API response, and create an array

my $data1 = $value->{_embedded}->{'rh:coll'};
print(Dumper($data1));


output:

$VAR1 = [
{
'_etag' => {
'$oid' => '571e0eb10fdcb17d700e586b'
},
'_id' => 'example.com',
'server_id' => '1',
'enabled' => '1'
},
{
'_etag' => {
'$oid' => '571e0eb90fdcb17d700e586c'
},
'_id' => 'example10.com',
'server_id' => '1',
'enabled' => '1'
}
];


I'm able to parse values using

print $value->{_embedded}->{'rh:coll'}->[0]->{_id} . "\t\n";
print $value->{_embedded}->{'rh:coll'}->[1]->{_id} . "\t\n";


output

example.com
example10.com


How can I create an array out of website names if enabled is set to 1?

I have tried looping thought this

foreach my $x (%$data1) {
print $x->{_id};
}

Answer

Here $data1 is array reference, so you should dereference it using @ {..}. Probably you want something like this:

my @sites;

foreach my $x( @ { $data1 } ) { 
  push( @sites, $x -> {_id} ) if( $x -> {enabled} ); # $x is hash reference
}

# now @sites contain all your sites from API response for which enabled is set to 1.
Comments