Gunnar Hjalmarsson wrote:
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;



#!/usr/bin/perl

use warnings;
use strict;

my $arrayRef = [ 1, 2, 3, ['a', 'b', 'c', ["Hello"] ]];

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



goksie

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to