#!/usr/bin/perl use warnings; while (<>) # the diamond operator to easily read files from the command line { # This is probably the hardest line in the program and yours will certainly vary # This one splits based on whitespace or " . , ( ) ! # Note that other characters (like $ or %) will be counted as part of a word @new_words = split /\s+|[".,()!]/, $_; foreach (@new_words) { if ($_) # recall that split returns empty fields if it finds { # delimiters side-by-side so ignore empty fields s/(.*)/\L$1/g; # convert the word to lowercase $word_count{$_}++; # add to hash } } } # Here we build a new list from the hash, storing each key to sort later # Notice that we ignore the value for the time being, we just care about the keys while ($key = each %word_count) { push @keys, $key; } # Sort the array of keys @keys = sort @keys; # Print the key-value pairs from the hash # Ordering the output based on the sorted @keys array foreach (@keys) { printf "%-20s %3s\n", $_, $word_count{$_}; }