http://www.perlmonks.org?node_id=1012884

jarrodb has asked for the wisdom of the Perl Monks concerning the following question:

Hello perl monks, I am trying to loop through an array but am stuck pulling my hair out! Hoping you can assist. In the following example, it appears that the first loop cannot get the correct size of the first array; yet using similar code for the second it works fine

$arrref = $queryHandle->fetchall_arrayref(); $colnames = $queryHandle->{NAME}; print Dumper($colnames); print Dumper($arrref); print "A size:" . @colnames . "\n"; for ($i=0; $i < @colnames; $i++) { print "A: " . $i . " : " . $colnames[$i] ."\n"; } for ($i=0; $i<= @arrref; $i++) { print "B size:" . @{$arrref->[$i]} . "\n"; for ($j=0; $j< @{$arrref->[$i]}; $j++) { print "B: " . $i . " : " . $j . " : " . $arrref->[$i]->[$j] . +"\n"; } }
C:\temp>perl 1.pl $VAR1 = [ 'MEASURE', 'CNT' ]; $VAR1 = [ [ '# PLTADM Queries (ex batch) ', '0' ] ]; A size:0 B size:2 B: 0 : 0 : # PLTADM Queries (ex batch) B: 0 : 1 : 0

Replies are listed 'Best First'.
Re: Looping through an Array
by toolic (Bishop) on Jan 11, 2013 at 13:21 UTC
    You should dereference your array refs:
    use warnings; #use strict; $colnames = [ 'MEASURE', 'CNT' ]; $arrref = [ [ '# PLTADM Queries (ex batch) ', '0' ] ]; my @colnames = @{ $colnames }; print "A size:" . @colnames . "\n"; for ($i=0; $i < @colnames; $i++) { print "A: " . $i . " : " . $colnames[$i] ."\n"; } for ($i=0; $i<= @arrref; $i++) { print "B size:" . @{$arrref->[$i]} . "\n"; for ($j=0; $j< @{$arrref->[$i]}; $j++) { print "B: " . $i . " : " . $j . " : " . $arrref->[$i]->[$j] . +"\n"; } } __END__ A size:2 A: 0 : MEASURE A: 1 : CNT B size:2 B: 0 : 0 : # PLTADM Queries (ex batch) B: 0 : 1 : 0

    Tip #1 from the Basic debugging checklist: strict. See also:

Re: Looping through an Array
by vinoth.ree (Monsignor) on Jan 11, 2013 at 13:25 UTC

    Have you included

    use strict; use warnings;

    There is no array with @colnames, so its printing 0, You have $colnames variable which has the array reference, you need to dereference it like

    print "A size:" . @$colnames . "\n";
Re: Looping through an Array
by Anonymous Monk on Jan 11, 2013 at 13:21 UTC
Re: Looping through an Array
by jarrodb (Initiate) on Jan 11, 2013 at 13:33 UTC
    Thanks, Yes I normally do use strict, however I started this one from a very old copy of a script I did many years ago. I tend to only come back to perl every few years as needs arise so the dereferencing throws me off sometimes. (especially after midnight and a long day at work!) Thanks again; great quick replies greatly appreciated.