Search code examples
perldata-dumper

Display data from an array of objects


I'm trying to display data from an array of objects obtained using another company's API, but I am getting errors when I attempt to using a foreach loop.

I'm using Dumper to display everything in the array.

print Dumper($object);

Partial output from Dumper:

'enable_dha_thresholds' => 'false',
  'members' => [
    bless( {
      'ipv4addr' => '192.168.1.67',
      'name' => 'name.something.com'
    }, 'Something::Network::Member' ),
    bless( {
      'ipv4addr' => '192.168.1.68',
      'name' => 'name.something.com'
    }, 'Something::Network::Member' )
  ],
  'comment' => 'This is a comment',

I'm trying to extract the "members" which appears to be a double array:

//this works    
print $members->enable_dha_thresholds(); 

//this works
print $members[0][0]->ipv4addr; 

//does not work
foreach my $member ($members[0]){
     print "IP". $member->ipv4addr()."\n";  
}

I receive this error: Can't call method "ipv4addr" on unblessed reference at ./script.pl line 12.

I'm not sure I entirely understand "blessed" vs "unblessed" in Perl since I am new to the language.


Solution

  • print $members[0][0]->ipv4addr; //this works

    so $members[0] is an array reference.
    You have to dereference the array:

    foreach my $member ( @{ $members[0] } ){
        print "IP". $member->ipv4addr()."\n";  
    }
    

    The error refering to an "unblessed reference" tells you you aren't using an object; rather you provide an array-reference, which isn't the same :)

    HTH, Paul