Deano
Deano

Reputation: 12190

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};
 }

Upvotes: 0

Views: 84

Answers (1)

Arunesh Singh
Arunesh Singh

Reputation: 3535

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.

Upvotes: 4

Related Questions