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

Greetings Monks, I have a file that looks something like this:
CS MS CS AT AV MS
What I need to do is count the occurrance of each, so the output based on the above should be
CS1 MS1 CS2 AT1 AV1 MS2
I figured the easiest way would be to do this using an array, but what I have below does not give me what I need.
open(PBXNUM1, ">pbxnum1"); open(MYINPUTFILE, "pbxnum"); $nt = 0; $ms = 0; $ap = 0; $cs = 0; $em = 0; $at = 0; $av = 0; $to = 0; while (<MYINPUTFILE>) { my($line) = $_; chomp($line); $nt++; $ms++; $ap++; $cs++; $em++; $at++; $av++; $to++; @mypbx = ('NT', 'MS', 'AP', 'CS', 'EM', 'AT', 'AV', 'TO'); foreach $mypbx (@mypbx) { print PBXNUM1 "$line$mypbx\n"; } }
Any suggestions?

Replies are listed 'Best First'.
Re: Counting within an array
by happy.barney (Friar) on Nov 30, 2010 at 13:48 UTC
    use hash:
    my %hash; while (<MYINPUTFILE>) { chomp; $hash{$_} ++; } $\ = "\n"; while (my ($k, $v) = each %map) { print $k, $v; }
      In order to meet the posted spec (output on every line), you can move the print statement into the while loop:

      my %hash; while (<MYINPUTFILE>) { chomp; $hash{$_} ++; print "$_$hash{$_}\n"; }
        That works like a charm, thank you very much.
Re: Counting within an array
by locked_user sundialsvc4 (Abbot) on Nov 30, 2010 at 14:22 UTC

    It is very useful to note how, in the first response, the statement e.g. $$somehash{$somekey}++ will automagically create a new hash-element, with a value of 1, if such a key does not presently exist.

    In fact, “incrementing an undef value” works in-general, producing a value of 1.   A delightful example of “DWIM = Do What I Mean.”

    One tiny consideration if you happen to be reading strings from a file:   don’t forget to chomp.   Otherwise, the strings you read might contain invisible “newline” characters which can make for irritating annoyance-bugs.

Re: Counting within an array
by ambrus (Abbot) on Dec 01, 2010 at 11:01 UTC

    awk '{ print $0(++a[$0]) }'
    Just kidding. Use the perl solution above instead.