Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to loop through an object? 1

Status
Not open for further replies.

whn

Programmer
Oct 14, 2007
265
US
I understand that a perl object is much like a hash ref, but not the 100% same.

For instance, it is easy to loop through a hash ref:

Code:
if(ref($var) eq 'HASH') {
  foreach my $key (keys(%{$var})) {
    print "Key: $key, Val: $var->{$key}\n";
  }
}


But I don't know how to loop through an object like:
Code:
my $obj = someModuleName->new();


If I knew the obj '$obj' has some data members, then I know how to reach it:
Code:
print "$obj->{dataMember1}\n";

Thanks in advance for your help.
 
Hiya,

you can still treat it like a hashref even though it's blessed:

Code:
foreach my $key (keys %{$obj}) {
  print $key." => ".$obj->{$key}."\n";
}

The ref() will tell you want kind of object it is. Did you also want to print out the subs?

Cheers,
Scott
 
Thank you, Scott!

Somehow, I remembered I did try your way once but did not success. Then I have never tried it again. I guess that I must have made some dumb mistake at my first try.

Thanks again for the solution. And yes, please show me how to print out the subs.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top