
rork
User
Jun 22, 2005, 12:04 AM
Post #13 of 18
(1385 views)
|
|
Re: [KevinR] Suggestions needed!!!
[In reply to]
|
Can't Post
|
|
I agree there is no easy way to do it, but it isn't impossible. (There are few things (if any) that are impossible with Perl)
#!perl use strict; use warnings; my %count = (); my @order; my %sorted; # open(DATA,'path/to/file.txt') or die "Can't open the file: $!"; while(<DATA>){ chomp; my (@words) = split(/\s+/); foreach my $word(@words) { unless (exists $count{$word}) { push @order, $word; } $count{$word}++; } } foreach my $word(@order) { unless (exists $sorted{$count{$word}}) { $sorted{$count{$word}} = []; } push @{$sorted{$count{$word}}}, $word; } foreach my $i(sort keys %sorted) { foreach my $word(@{$sorted{$i}}) { print "$count{$word} = $word\n"; } } __DATA__ testing test test This is a testing program test test test test test test Remove the # before open en everything from __DATA__ to the end to adapt it for opening a file. I'll try to explain. I use an array (@order) to memorize the order words were found in, if a word already appeared in the hash and in the array it's not added. Arrays have a fixed order, the keys of a hash don't. Then I itter over the array storing the data in a hash (%sorted). The key is the times a word is found, the value is an array reference containing all the words that are found that many times. Now I sort %sorted and print the output: 1 = This 1 = is 1 = a 1 = program 2 = testing 8 = test -- Don't reinvent the wheel, use it, abuse it or hack it.
|