Re: Looping through an anonymous array of arrays

[email protected] (Gunnar Hjalmarsson)
Newsgroups perl.beginners
Message-ID <[email protected]>
Rodrick Brown wrote:
> my $arrayRef = [ 1, 2, 3, ['a', 'b', 'c', ["Hello"] ]];
> 
> I have no problem returning single elements but how would one walk this list
> of elements with say a for loop?

One way:

     my $level = 0;
     breakdown( $arrayRef );

     sub breakdown {
         my $ref = shift;
         foreach my $elem ( @$ref ) {
             if ( ref($elem) eq 'ARRAY' ) {
                 $level++;
                 breakdown( $elem );
                 $level--;
             } else {
                 print "\t" x $level, "$elem\n";
             }
         }
     }

But as usual when we are dealing with nested data structures, 
Data::Dumper comes in handy:

     use Data::Dumper;
     print Dumper $arrayRef;

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.