Re: Looping through an anonymous array of arrays

[email protected] ("Chas. Owens")
Newsgroups perl.beginners
Message-ID <[email protected]>
On Fri, Jun 6, 2008 at 9:31 PM, Rodrick Brown <[email protected]> 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?
>

You can treat an array reference like an array by prefixing it with an
@ (this is called dereferencing):

for my $item (@$arrayRef) {
    if (my $type = ref $item) {
        print "item is a $type reference\n";
    } else {
        print "item is $item\n";
    }
}

If you just want to print out the items held in the data structure you
can use a recursive function:

sub print_it {
        for my $item (@_) {
                if (ref $item) {
                        print_it(@$item);
                        next;
                }
                print "$item ";
        }
}

print_it($arrayRef);

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
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.