in reply to Re: using hashes to count
in thread using hashes to count

Thank you both of your replies. Yes i am just counting up the occurrences of the strings. What i am worried is, without the 'exists' check, $rh_count->{$keyword}++ would give a warning since it would be undef (provided that it wouldnt have been used before)

Replies are listed 'Best First'.
Re^3: using hashes to count
by Joost (Canon) on Jun 14, 2007 at 23:13 UTC
Re^3: using hashes to count
by nferraz (Monk) on Jun 15, 2007 at 09:43 UTC

    Usual way:

    my @strings = qw/ a a b c a b c d e a b c a b c d /; my %count; foreach ( @strings ) { $count{$_} ||= 0; $count{$_}++; } # Then, if you want to sort the results by value: foreach ( sort { $count{$a} <=> $count{$b} } keys %count ) { print "$_ => $count{$_}\n"; }
      The $count{$_} ||= 0; is useless. ++ doesn't give undefined warnings.
      Excellent, thank you very much.