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

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

not sure how to title this post.

the code below gives the count i need, but i'm having trouble printing the count where i need it, which is in the third position. i've tried splice and other things, but i have to do that before the last statement, so i get a wrong count.
my $accounts_by_id = {}; for (@accounts) { my($id, $rest) = split /,/, $_, 2; $accounts_by_id->{$id}->{info} = $rest; } for (@purchases) { my($id, $rest) = split /,/, $_, 2; push @{$accounts_by_id->{$id}->{purchases}}, $rest; } for (@accounts) { my($id, $rest) = split /,/, $_, 2; { my @five = splice @{$accounts_by_id->{$id}->{purchases}}, 0, 5; last unless @five; #I NEED TO COUNT AND PRINT THE NUMBER OF ITEMS IN @FIVE HERE BUT I HAV +EN'T INCREMENTED THE COUNTER YET print "$id,$accounts_by_id->{$id}->{info},", join(',', @five), "\n"; $count =0; foreach $id(@five){ $count ++; } #THIS GIVES ME THE RIGHT COUNT print "count is: $count endcount"; print "<br>"; redo if @five == 5; } }

Replies are listed 'Best First'.
Re: adding a count before the limit?
by dragonchild (Archbishop) on May 06, 2005 at 18:13 UTC
    Then why don't you increment the counter first? Or, just do my $count = @five;

    • In general, if you think something isn't in Perl, try it out, because it usually is. :-)
    • "What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?"
Re: adding a count before the limit?
by tlm (Prior) on May 06, 2005 at 21:58 UTC

    Just to clarify dragonchild's second suggestion: does this do what you need?

    my $count = @five; print "$id,$accounts_by_id->{$id}{info},$count", join(',', @five), "\n";

    the lowliest monk

Re: adding a count before the limit?
by malaga (Pilgrim) on May 07, 2005 at 02:47 UTC
    perl either makes me feel like a genius or a moron. this time - moron. thanks for your help - it worked perfectly.
    Malaga
Re: adding a count before the limit?
by malaga (Pilgrim) on May 06, 2005 at 18:21 UTC
    because then i get a count of say, 12 on each line that matches instead of 5 and 5 and 2. i only get the right count after the join.
    any clues for the clueless?
    Malaga