PuffedRiceCrackers
PuffedRiceCrackers

Reputation: 785

Iterating over an array reference

# data $bug
{ 
 'keyword_objects' => [ 
    bless( { 'id' => 15, 'name' => 'CRASH'}, 'SomeModule::SomeFilename' ), 
    bless( { 'id' => 6, 'name' => 'CUSTOMER' }, 'SomeModule::SomeFilename' ) ],
 'category' => 'error'
}
   foreach my $keyword ($bug->{keyword_objects}) {
     print Dumper($keyword);
   }

It prints the whole of keyword_objects instead of the individual items in it. Now it should be obvious to you that I know so little about Perl, I'd like to also ask what is the right way to reference name in each keyword.

Upvotes: 1

Views: 249

Answers (1)

simbabque
simbabque

Reputation: 54381

To iterate over the elements in your array ref, you need to dereference it. foreach needs a list.

foreach my $keyword ( @{ $bug->{keyword_objects} } ) {

Your objects are hash references, so you could reach into their internals like this:

$keyword->{name}

However, messing with internals is not a good idea. Instead, you should write accessors and call them as a method.

$keyword->name

Upvotes: 5

Related Questions