#!/bin/usr/perl -w ################################################################ # # Name: count_words # Count words in a file # Author: Bill Kraynek # Created: April 1, 2007 # ################################################################# open( IN , $ARGV[0] ) || die "Error : Cannot open file $ARGV[0]."; %words = (); while ( ) { @line = split(/[^a-zA-Z]+/); foreach (@line) { if ( $_ ) { tr/[A-Z]/[a-z]/; $words{$_}++ } } } @sortedkeys = sort keys(%words); print "\nWords in sorted order:\n\n"; foreach (@sortedkeys) { print "$_ appeared $words{$_} " . adds($words{$_}) . "\n"; } @sortedvalues = sort by_count keys(%words); print "\nWords in word count order:\n\n"; foreach (@sortedvalues) { print "$_ appeared $words{$_} " . adds($words{$_}) . "\n"; } sub by_count { -($words{$a} <=> $words{$b}); } sub adds { $times = "times"; if ( $_[0] == 1 ) { chop($times) } return $times; }