dalziel has asked for the wisdom of the Perl Monks concerning the following question:

I'm using the XML::FOAF parser to grab lists of links from a site. It creates the object ok, but when I get the 'knows' array, which is an array of all the people this person knows, I can't seem to loop through the array:
my $foaf = XML::FOAF->new(URI->new('http://glenn.typepad.com/foaf.rdf' +)); my $person = $foaf->person; my @people = $person->knows;
If I say print $people[0][0]->name; it prints out the name of the first person, but
foreach (@people[0) { print $_; }
doesn't print out the names of all the people, it just seems to return person as itself (ie if I put
my @pp = $_; print $pp[0][0]->name;
inside the loop it works) I'm not sure why it needs the array of array ($people[0][0]) but I've tried it without that & it doesn't work. Am I missing something blindingly obvious here?

Replies are listed 'Best First'.
Re: Looping through an array of objects
by graff (Chancellor) on Jan 19, 2004 at 02:25 UTC
    If this works:
    print $people[0][0]->name;
    then looping would work like this:
    foreach ( @{$people[0]} ) { print $_->name; }
    Or you could do it like this:
    foreach $row ( @people ) { foreach $cell ( @$row ) { print $cell->name; } }
    The point is that each element in @people is itself an array reference, and needs to be treated as such. In the first example, in order to dereference an element of @people as an array, you need the curly braces between the "@" and the expression that represents the array ref.

    In the second example, doing the dereferencing in two stages makes the syntax less messy. At each iteration of the outer loop, $row is set to the array ref for the inner dimension of @people, and is easier to dereference.

      Thankyou, you've saved me a lot of trouble. It would apear that I missed the "Returns a reference to an array" in the CPAN doco. /slaps forehead