http://www.perlmonks.org?node_id=457784

ghenry has asked for the wisdom of the Perl Monks concerning the following question:

You want to search a file for unique words, count them and print a summary, but also saving these results for later use.

Using a simple database (a dbm file), you could do (adapted from Perl Cookbook, 2ed):

#!/usr/bin/perl use strict; use warnings; # Basename of Simple Database file my $DBFILE = 'wordcount_db'; # open database, accessed through %WORDS dbmopen (my %WORDS, $DBFILE, 0666) or die "Can't open $DBFILE: $!\n"; # Make a word frequency counter while (<>) { while ( /(\w['\w-]*)/g ) { $WORDS{lc $1}++; } } # Output hash in a descending numeric sort of its values foreach my $word ( sort { $WORDS{$b} <=> $WORDS{$a} } keys %WORDS) { printf "%5d %s\n", $WORDS{$word}, $word; } # Close the database dbmclose %WORDS;

TIMTOWTDI however.

Originally posted as a Categorized Question.