W
wana
This morning, I wrote a little script to count words in a file. I did
this one on my pda, which happened to have 'Moby Dick' saved on the
storage card. Writing Perl scripts on the pda is a little like
playing video games... I wanted to print to a file the list of words
and the number of occurrence in descending order of occurrence. The
following seemed to work, although I initially did my counting loops
wrong and only counted the first occurrence per line. I was wondering
if I got it right and if there is a better way to do it. 'Programming
Perl' mentions the Schwartzian map-sort-map technique which I thought
might apply. Also, the loop that does the counting below; I tried it
this way:
$words{lc $1}++ while /(\w+)/gi for (<INF>);
but it did not work.
#!/usr/bin/perl
use strict;
my $fn = "/textucation/moby10b.txt";
open (INF, $fn) or die "error: $!";
my %words;
for (<INF>)
{
$words{lc $1}++ while /(\w+)/gi;
}
my @n = %words;
@n = reverse @n;
%words = @n;
my @k = keys %words;
sub num {$b <=> $a}
@k = sort num @k;
open (OUTF, ">file count.txt") or die "error: $!";
print OUTF "$_ $words{$_}\r\n" for (@k);
thanks!
wana
this one on my pda, which happened to have 'Moby Dick' saved on the
storage card. Writing Perl scripts on the pda is a little like
playing video games... I wanted to print to a file the list of words
and the number of occurrence in descending order of occurrence. The
following seemed to work, although I initially did my counting loops
wrong and only counted the first occurrence per line. I was wondering
if I got it right and if there is a better way to do it. 'Programming
Perl' mentions the Schwartzian map-sort-map technique which I thought
might apply. Also, the loop that does the counting below; I tried it
this way:
$words{lc $1}++ while /(\w+)/gi for (<INF>);
but it did not work.
#!/usr/bin/perl
use strict;
my $fn = "/textucation/moby10b.txt";
open (INF, $fn) or die "error: $!";
my %words;
for (<INF>)
{
$words{lc $1}++ while /(\w+)/gi;
}
my @n = %words;
@n = reverse @n;
%words = @n;
my @k = keys %words;
sub num {$b <=> $a}
@k = sort num @k;
open (OUTF, ">file count.txt") or die "error: $!";
print OUTF "$_ $words{$_}\r\n" for (@k);
thanks!
wana