in reply to counting lines in perl

This is failry concise:

#!/usr/bin/perl use strict; my (%words, $key); open(FILE, "<test.txt"); while(<FILE>) { chomp($_); $words{$_}++; } close(FILE); foreach $key (keys %words) { print "$words{$key} $key\n"; } exit;


davidj

Replies are listed 'Best First'.
Re^2: counting lines in perl
by chas (Priest) on Feb 27, 2005 at 06:30 UTC
    But that code doesn't seem to count groups of consecutive repetition just once, does it? - (which is what I thought the original poster wanted.)
    chas
    (Update: Actually, now that I've gone to a system where I could try out uniq -c, I see that I misunderstood what was desired so my code doesn't seem to do what the original poster wanted. Your code is closer, but the output isn't the same as that of uniq -c, at least the version I used. Sorry about the confusion...)
      You are correct. My code is flawed. For some reason I thought uniq -c sorted the file first, but it doesn't. My mistake.

      davidj