cosmicperl has asked for the wisdom of the Perl Monks concerning the following question:
Now I sometimes I want to know the array item number so I end up doing a for:-my $ref; $ref = [ { "key1" => 'a', "key2" => 'b', }, { "key1" => 'c', "key2" => 'd', }, ]; foreach $hashref (@{$ref}) { print $hashref->{'key1'}; }#foreach
As you can see the print is much longer, when the data structure is more complex this can be a really big difference.for (my $item = 0; $item <= $#{$ref}; $item++) { print $item; print $ref->[$item]->{'key1'}; }#for
Most the time the data is loading from files and I do not know how the foreach loop with deal with missing array items, such as:-my $item = 0; foreach $hashref (@{$ref}) { print $hashref->{'key1'}; $item++; }#foreach
my $ref; $ref->[0]->{'key1'} = "a"; $ref->[5]->{'key1'} = "b"; my $item = 0; foreach $hashref (@{$ref}) { print $item; print $hashref->{'key1'}; $item++; }#foreach
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: looping through array references
by GrandFather (Saint) on Feb 03, 2008 at 18:20 UTC | |
|
Re: looping through array references
by bobf (Monsignor) on Feb 03, 2008 at 20:31 UTC | |
|
Re: looping through array references
by hipowls (Curate) on Feb 03, 2008 at 20:17 UTC | |
by johngg (Canon) on Feb 04, 2008 at 00:08 UTC |