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.
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
It's an issue of "array reference" vs. "array". $members[0]
is an array reference; the foreach
operator works with arrays (or lists, to be pedantic). You will want to say
foreach my $member ( @{$members[0]} ) { ...
to iterate over the elements that $members[0]
refers to.
The syntax is tricky, and you will probably make a few more mistakes along the way with this stuff. The relevant docs to get you up to speed are in perlref
(or perlreftut
), perllol
, and also perldsc
and perlobj
.
"blessed" by the way, means that a reference "knows" what kind of object it is and what package it should look in to see what methods it can run. When you get an "unblessed reference" warning or error, that usually means you passed something that was not an object somewhere that expected an object -- in this case, $members[0]
is the unblessed reference while you intended to pass the blessed references $members[0][0]
, $members[0][1]
, etc.
精彩评论