#!/usr/bin/perl use strict; use warnings; sub readWords { ## Gets how many of each word are in a file and returns a hash my $file = shift; my %words = (); my $currentWord = ""; # What characters to ignore my $blacklist = '[\s~`!@#\$%\^&\*\(\)\{\}\+=\\\/\[\]\.\,<>\?;:"]'; open(my $FILE, "<", $file) or die("$0: $file: $!\n"); while(!eof($FILE)) { while(read($FILE, my $letter, 1)) { if($letter !~ /$blacklist/) { $currentWord .= lc($letter); } else { last; } } if(!defined($words{$currentWord})) { $words{$currentWord} = 0; } $words{$currentWord}++; $currentWord = ""; } close($FILE); return %words; } sub main() { my %words = readWords($ARGV[0]); my @keys = keys(%words); my @commonWord = ("", 0); foreach my $key (sort(@keys)) { if($words{$key} > $commonWord[1]) { @commonWord = ("$key", $words{$key}); } print("$key: $words{$key}\n"); } print("Number of unique words: " . scalar(@keys) . "\n"); print("Most common word: $commonWord[0] - used $commonWord[1] times\n"); } main();