in reply to looping through array references

I use the following because it limits the scope of the two variables, $item and $hash_ref, to the loop where they are used.

for my $item ( 0 .. $#{$ref} ) { $hash_ref = $ref->[$item]; print "$hash_ref->{'key1'}; }
It also continues to work when you add extra code that includes a next or redo statement.

Update fixed code thanks to johngg. Teach me to post without running it first;)

Replies are listed 'Best First'.
Re^2: looping through array references
by johngg (Canon) on Feb 04, 2008 at 00:08 UTC
    I think there are a couple of problems with your code:

    • for my $item ( 0 .. @{$ref} ) is going to try to access an element beyond the end of the array. What you need here is $#{$ref}.

    • $hash_ref = $ref->{$item}; should be $hash_ref = $ref->[$item]; as you are dereferencing an array, not a hash

    Cheers,

    JohnGG