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

I wan't to loop through an array which is multidimensional. Foreach does loop the correct amount of times, but does not reference the array correctly?
$items[0]{title} = "Song 2"; $items[0]{artist} = "Blur"; $items[1]{title} = "The Call of Khtulu"; $items[1]{artist} = "Metallica"; $x = "0"; foreach $item ($items) { print $items[x++]{title}; #This works print $item{title}; #But this doesn't. Why not? }

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I loop through a multidimensional array?
by davorg (Chancellor) on Jul 04, 2001 at 13:23 UTC

    A few typos that were hopefully transcription errors: foreach $item ($items) should be foreach $item (@items) and $items[x++]{title} should be $items[$x++]{title}.

    But your main problem is that in the loop each value of $item is a hash reference (not a hash), so you need to use

    print $item->{title};

    And incidently, why do you initialise $x as a string, when you only ever use it as a number?

    Originally posted as a Categorized Answer.

Re: How do I loop through a multidimensional array?
by razzie (Initiate) on Jul 04, 2001 at 15:09 UTC
    Thank you very much! You're correct, those other errors where typos generated by a combination of too much sleep and too little coffee (or was it the other way around?) when simplifying the question into an example. Your suggestion was just the elegant solution I was looking for, thanks! The corrected example would then be:
    $items[0]{title} = "Song 2"; $items[0]{artist} = "Blur"; $items[1]{title} = "The Call of Khtulu"; $items[1]{artist} = "Metallica"; foreach $item (@items) { print $item->{artist}; print $item->{title}; }

      Actually, your data structure initialisation could be a little more elegant too. Try this:

      my @items = ({ title => 'Song 2', artist => 'Blur' }, { title => 'The Call of Khtulu', artist => 'Metallica' });

      Oh, and I knew that Metallica aren't very intelligent, but can they really not spell "Cthulhu"?

      --
      <http://www.dave.org.uk>

      Perl Training in the UK <http://www.iterative-software.com>