word_freq.pl in Perl
A word-frequency report over an inline passage, driven by one hash.
use strict;
use warnings;
# word_freq: count word occurrences in an inline passage
my $text = <<'TEXT';
The quick brown fox jumps over the lazy dog.
The dog barks; the fox runs. Quick thinking, that fox.
TEXT
my @words = lc($text) =~ /[a-z]+/g;
my %freq;
$freq{$_}++ for @words;
printf "words total: %d\n", scalar @words;
printf "words unique: %d\n", scalar keys %freq;
my @ranked = sort { $freq{$b} <=> $freq{$a} or $a cmp $b } keys %freq;
print "top 5:\n";
for my $word (@ranked[0 .. 4]) {
printf " %-8s %d\n", $word, $freq{$word};
}
my @once = sort grep { $freq{$_} == 1 } keys %freq;
print "seen once: ", join(", ", @once), "\n";
How it works
- A list-context match,
lc($text) =~ /[a-z]+/g, pulls every lowercase word. $freq{$_}++ for @wordsbuilds the whole frequency table in one line.- A two-key
sortranks by count, then alphabetically to break ties. grep { $freq{$_} == 1 }filters out the words seen only once.
Keywords and builtins used here
forgrepjoinkeyslcmyprintprintfscalarsortuse
The run, in numbers
- Lines
- 27
- Characters to type
- 642
- Tokens
- 155
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 116 seconds.
Step 1 of 3 in Encore, step 25 of 27 in Language basics.