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

hi there, I have a bit more complex structure (array of hash) that I am trying to loop over with FOREACH, but I am having trouble accessing the values. From the snippet below, I am trying to display: foo --> bar as well as content --> perlmonks.org but with my code I am only able to get the key, not the value, e.g: foo ARRAY(0x8e8598c)
'main' => { 'ResultSet' => { 'foo' => 'bar', 'Listing' => [ { 'car' => '0.5', 'url' => { 'content' => 'pe +rlmonks.org', 'type' => 'body' }, }, { 'car' => '0.16', 'url' => { 'content' => 'so +meotherurl.com', 'type' => 'body' }, } ] } } [% FOREACH item IN data.keys.sort %] [% IF item == 'main' %] [% FOREACH m IN data.main.keys.sort %] [% IF m == 'ResultSet' %] [% FOREACH list IN data.main.ResultSet.Listing.keys.sor +t %] [% IF list == 'foo' %] <tr><td>[% list %]</td>[% data.main.ResultSet.Listi +ng.$list %]</tr> [% ELSIF list == 'url' %] [% FOREACH u IN data.main.ResultSet.Listing.url %] [% IF u == 'content' %] <tr><td>test 3</td>[% u.content %]</tr> [% END %] [% END %] [% END %] [% END %] [% END %] [% END %] [% END %] [% END %]

Replies are listed 'Best First'.
Re: Template Toolkit's FOREACH
by Tanktalus (Canon) on Mar 01, 2008 at 00:57 UTC

    First off, it helps if you actually post code that works as-is (the __END__ marker with the *DATA filehandle is very handy for this). Or, in this case, doesn't work, but is at least in a state that can show what you mean...

    Next, that's pretty messy. Why are you looping through and then checking for only one particular value? Without testing, I think you mean:

    <!-- you only use 'foo', so why loop and check for it? --> <tr><td>foo</td>[% data.main.ResultSet.Listing.foo %]</tr> [% FOREACH l IN data.main.ResultSet.Listing %] <tr><td>test 3</td>[% l.url.content %]</tr> [% END %]
    There's only one place in your sample where you're not only looping, but you're using all the values you loop over. The rest seem to be hard-coded...

Re: Template Toolkit's FOREACH
by Anonymous Monk on Mar 04, 2008 at 01:01 UTC
    thanks