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

I'm getting back into Perl after being away for a few months and am running into a problem with some of my "old" code. I have a loop that grabs a company ID from a file and pushes it into an array called COMPANIES. It then executes the code below which works, except that the count for each unique company is zero. I'm thinking the 'count' (which is only mentioned here, no where else in the code) is the problem but when I try to add a "counter" that doesn't work. Can someone tell me what i'm doing wrong?
foreach (@COMPANIES) { $sum{$_->{'comp'}} += $_->{'count'}; } #Output in %sum use Data::Dumper; print OUTFILE Dumper(\%sum);

Replies are listed 'Best First'.
Re: Count not working
by kennethk (Abbot) on Jul 14, 2010 at 17:33 UTC
    If count is never defined, it is undef and hence equal to 0 in numeric context. If you are just trying to accumulate the number of times you encounter a certain value of comp, perhaps you mean:

    foreach (@COMPANIES) { $sum{$_->{comp}}++; }

    Note that since Perl automatically stringifies alphanumeric hash keys, you don't need to include quotes in this context.

      That worked, thanks! And thanks for the tip about the quotes.