Re: Looping through an anonymous array of arrays

[email protected] ((Randal L. Schwartz))
Newsgroups perl.beginners
Organization Stonehenge Consulting Services; Portland, Oregon, USA
Message-ID <[email protected]>
>>>>> "Aruna" == Aruna Goke <[email protected]> writes:

Aruna> for my $item (@$arrayRef){
Aruna> print $item unless ref($item) eq 'ARRAY';
Aruna>      if(ref($item) eq 'ARRAY'){
Aruna>        for my $item1(@$item){
Aruna>        print $item1 unless ref($item1) eq 'ARRAY';
Aruna>             {
Aruna>         if(ref($item1) eq 'ARRAY'){
Aruna>             print @$item1;
Aruna>         }
Aruna>          }
Aruna>   }
Aruna>   }
Aruna> }

This handles only *two* levels.  It would break on three or more.
Other solutions would work fine for more.  I'll even throw mine in:

    my @items = @$arrayRef;
    while (@items) {
      if (ref $items[0]) {
        if (ref $items[0] eq "ARRAY") {
          unshift @items, @{shift @items}; # replace arrayref with contents
          redo;
        }
        die "cannot handle ref of type ", ref $items[0];
      }
      print shift @items;
    }

Untested, but I often get this stuff right. :)

Note that unlike the recursive solutions, this solution is *not*
recursive and not subject to the 100-recursion limit in Perl.

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<[email protected]> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.vox.com/ for Smalltalk and Seaside discussion
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.