iterating through perl object fields

M

Mafj

Hi,

I am a complete beginner I tried to find some information on the
topic, however, I have only found how to deal with arrays and
associative arrays. All documentation seems to be helpless with an
object/structure.

I have a fixed structure like this (comes from external file):

$self->{data} = {
'ver' => 2,
'list' => {
'name1' => 'item1',
'different_name' => 'another_item',
'whatever' => 'special_item',
# and 1000 more
}
};
I need a content of $self->{data}->{list}. I do knot know field names
nor keys.
There is probably some simple loop, foreach or while,e.g.
( ($c,$v) = each %self->{data}->{list} ).
But I cannot figure out the details that would finally let it work.
Help...
 
S

Sherm Pendley

Mafj said:
I have a fixed structure like this (comes from external file):

$self->{data} = {
'ver' => 2,
'list' => {
'name1' => 'item1',
'different_name' => 'another_item',
'whatever' => 'special_item',
# and 1000 more
}
};
I need a content of $self->{data}->{list}. I do knot know field names
nor keys.
There is probably some simple loop, foreach or while,e.g.
( ($c,$v) = each %self->{data}->{list} ).

You're pretty close. To begin with, since $self->{data}->{list} is a
reference to a hash, you need to dereference it with %$ in order to work
with the hash it refers to.

And second, you can get a list of hash keys with the keys (perldoc -f
keys) function:

my @listKeys = keys(%$self->{data}->{list});

sherm--
 
J

John W. Krahn

Sherm said:
You're pretty close. To begin with, since $self->{data}->{list} is a
reference to a hash, you need to dereference it with %$ in order to work
with the hash it refers to.

And second, you can get a list of hash keys with the keys (perldoc -f
keys) function:

my @listKeys = keys(%$self->{data}->{list});

ITYM: my @listKeys = keys %{$self->{data}->{list}};

$ perl -le'
my $self = { data => { list => { "a" .. "f" } } };
print for keys %$self->{data}->{list};
'
Type of arg 1 to keys must be hash (not hash element) at -e line 3, near
"};"
Execution of -e aborted due to compilation errors.




John
 
S

Sherm Pendley

John W. Krahn said:
ITYM: my @listKeys = keys %{$self->{data}->{list}};

Yep, you're right. That's what I get for banging out code in a post
without testing it. :-(

sherm--
 
M

Mafj

Thanks guys the following finally work:

eval `cat ./datafile.pl`;
foreach $x( keys %{$self->{data}->{list} } )
{
print "$x $self->{data}->{list}->{$x}\n";
}
Once again thanks for dropping me line.

Regards,
Maciej
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top