#To Run: Type start.pl on the command line. #The script should prompt you to enter a word or phrase. #Once you've done that, it'll prompt you for another one. #Then you will be told if the two terms are anagrams or not. #!/usr/bin/perl -w use strict; #I have to use this to make STDIN work. IDK why. $|=1; #variables my $aWord; my $bWord; my $word; my $sortWord; my $sortWords; my @words; my %anaHash; print "\nReady to play the anagram game? Excellent.\n\nType your first word or phrase, then hit Enter.\n\n"; $aWord = ; chomp $aWord; print "\n\nThanks! Now type your second word or phrase and hit Enter.\n\n"; $bWord = ; chomp $bWord; #This foreach loop performs the following tasks: #1. Pushes the two words from STDIN into an array (unsure if this is really necessary) #2. lowercases everything and removes all characters except for letters & spaces #3. splits both words into characters, sorts them alphabetically, then joins the sorted letters into a single "word" #4.pushes the array into a hash @words = ($bWord, $aWord); foreach $word (@words) { $word =~ tr/A-Z/a-z/; $word =~ s/[^a-z ]//ig; $sortWord = join '', sort(split(//, $word)); push @{$anaHash{$sortWord}}, $word; } #This foreach loop tries to determine if the word pairs are anagrams or not. foreach $sortWords (values %anaHash) { #"if you see the same word twice AND the input was two identical words:" if (1 < @$sortWords && @$sortWords[0] eq @$sortWords[1]) { print "\n\nFALSE: Your phrases are identical!\n\n"; } #"if you see the same word twice AND the input was two different words (i.e. a real anagram):" elsif (1 < @$sortWords && @$sortWords[0] ne @$sortWords[1]) { print "\n\nTRUE: @$sortWords[0] and @$sortWords[1] are anagrams!\n\n"; } #this is a failed attempt to identify pairs that are identical except one has extra spaces. Right now, this fails and falls into the "else" category below. elsif (@$sortWords[0] =~ m/ +@$sortWords[-1]/ || @$sortWords[-1] =~ m/ +@$sortWords[0]/) { print "\n\FALSE: @$sortWords[0] and @$sortWords[-1] are NOT anagrams. Spaces are characters, too!\n\n"; } #This is supposed to identify anything that's not an acronym. But the output prints twice! It's maddening!!!! else { print "Sorry, that's not an anagram pair\n"; } }