in reply to Counting frequency of strings in files

#!/usr/bin/perl -w use strict; print "Enter the name of your file, ie myfile.txt:\n"; chomp(my $val = <STDIN>); my %seen; open my $fh, '<', $val or die "wrong filename: $!"; while (defined(my $line = readline $fh)){ my @list = split "\t", $line; @seen{@list} = map{$seen{$_}||0+1} @list ; } #while(my($string, $count) = each %seen){ foreach my $key(sort {$seen{$b} <=> $seen{$a}} keys %seen){ my $string = $key; my $count = $seen{$key}; print "Number of instances of '${string}' found: $count\n"; }

Replies are listed 'Best First'.
Re^2: Counting frequency of strings in files
by Cian (Initiate) on Apr 23, 2012 at 18:03 UTC
    your script is close alright, but it seems to give a count of 1 for everything, even though i know there is more than one of most... I also want to have the script create an output text file and put the results there.
      Sorry, there should be this:
      @seen{@list} = map{($seen{$_}||0)+1} @list;

      and to print the output into a file, just say:
      open my $output_fh, '>', "filename.txt" or die $!; #while(my($string, $count) = each %seen){ foreach my $string(sort {$seen{$b} <=> $seen{$a}} keys %seen){ my $count = $seen{$string}; printf $output_fh "%-70s%d\n", $string, $count; } close $output_fh;