in reply to Word Comparison
which printsmy $word = 'bantha fodder'; my @letters = split//, lc($word); my %counts; for(@letters){ $counts{$_}++; } for(sort {$counts{$b} <=> $counts{$a}} keys %counts){ my $t = $_ =~ /[a-z]/ ? 'letter' : $_ =~ /[0-9]/ ? 'number' : 'character'; my $s = $counts{$_} > 1 ? 's' : ''; printf " the %-10s: %-3s ocurred %-3s time%s\n", $t,$_,$counts{$_},$s }
Now wrap that in a subroutine and use some loop control:the letter : 'a' ocurred 2 times the letter : 'd' ocurred 2 times the letter : 'e' ocurred 1 time the letter : 'n' ocurred 1 time the letter : 'r' ocurred 1 time the character : ' ' ocurred 1 time the letter : 'h' ocurred 1 time the letter : 'b' ocurred 1 time the letter : 'f' ocurred 1 time the letter : 't' ocurred 1 time the letter : 'o' ocurred 1 time
Now you can modify the loop / conditional as you see fit.sub letter_counts { my @letters = split//, lc(shift); my %counts; for(@letters){ $counts{$_}++; } return %counts } my $word1 = 'bantha fodder'; my $word2 = 'banana slug'; my %counts1 = letter_counts($word1); my %counts2 = letter_counts($word2); my $result = 'are equivalent'; test_loop: for(keys %counts1, keys %counts2){ if(!defined $counts2{$_} || !defined $counts1{$_}){ $result = 'are not equivalent'; last test_loop } } print "'$word1' and '$word2' $result\n";
|
|---|