-5

I'm new to perl. Can anyone give an example to a perl code for detecting anagram between to given strings using hash's. two strings - pool and polo.

  • See also [Word::Anagram](https://metacpan.org/pod/Word::Anagram) and [rosetta code: anagrams](https://rosettacode.org/wiki/Anagrams/Deranged_anagrams#Perl) – Håkon Hægland Mar 24 '19 at 19:22
  • Much appreciate for your help. rosetta code: anagrams seems to be complicate for me to understand. can you show me some source with basic syntax. – rising_thunder Mar 24 '19 at 19:45
  • You are welcome. The rosetta code looks quite simple, please explain what part of the code you do not understand. You could also take a look at the source code of the `Word::Anagram` module. You can find it [here](https://metacpan.org/release/Word-Anagram/source/lib/Word/Anagram.pm) – Håkon Hægland Mar 24 '19 at 19:50

1 Answers1

1
sub key(_) { join "", sort split //, $_[0] }

if (key("pool") eq key("polo") {
   say "Pool and polo are anagrams of each other.";
} else {
   say "Pool and polo aren't anagrams of each other.";
}

If you had a dictionary,

sub key(_) { join "", sort split //, $_[0] }

my $dict_qfn = "...";
my $search = "pool";

my %anagrams;
{
   open(my $fh, '<', $dict_qfn)
      or die("Can't open \"$dict_qfn\": $!\n");

   while (<$fh>) {
      chomp;
      push @{ $anagrams{ key($_) } }, $_;
   }
}

my @results = grep { $_ ne $search } @{ $anagrams{$search} // [] };
say "Anagrams of $search: ".( @results ? "@results" : "[none]" );
ikegami
  • 322,729
  • 15
  • 228
  • 466
  • Any particular reason for using `(_)`? (since you still write `key($_)`) Just feeling like using prototypes lately, or ... ? – Dada Mar 24 '19 at 22:57
  • @Dada, I'm not taking advantage of it, but it's exactly the kind of function where the prototype could be useful – ikegami Mar 24 '19 at 23:21