in reply to Count of patterns in a file without knowing pattern in advance

Use a hash, that way you only need to take one pass over the file:

#!/usr/bin/env perl use strict; use warnings; my %terms; for (<DATA>) { chomp; $terms{$_}++; } for my $key (keys %terms) { print "$key appeared $terms{$key}\n"; } __DATA__ one two three one five two ten one

Update: Well it's very pleasing to find that no less a luminary than Brother choroba has arrived at the exact same answer, albeit of course much faster!

  • Comment on Re: Count of patterns in a file without knowing pattern in advance
  • Download Code

Replies are listed 'Best First'.
Re^2: Count of patterns in a file without knowing pattern in advance
by cklatsky (Initiate) on Jun 07, 2019 at 18:37 UTC
    Thanks to both for the solution. I have that working now.
      There is usually a "one liner" alternative for simple requirements.

      I offer:

      perl -anE "$h{$F[0]}++}{say qq|$_ appeared $h{$_}| for sort keys %h" +*YOUR-FILE*
      Use single quotes if you are on Linux.

                      Time is an illusion perpetrated by the manufacturers of space.

        Unfortunately, this experimental feature no longer exists in perl version 5.24.1 and forward...produces the following error message:

        "Experimental keys on scalar is now forbidden at -e line 1."

        "It's not how hard you work, it's how much you get done."