summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--005/ch1.pl31
1 files changed, 31 insertions, 0 deletions
diff --git a/005/ch1.pl b/005/ch1.pl
new file mode 100644
index 0000000..1d020a6
--- /dev/null
+++ b/005/ch1.pl
@@ -0,0 +1,31 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+
+# Functional implementation (tail-recursive)
+sub anagrams {
+ sub iter {
+ my ($word, @acc) = @_;
+ if (length($word) == 0) {
+ return @acc;
+ } else {
+ my ($head, $tail) = $word =~ /^(.)(.*)$/;
+ @_ = $tail; # Next word will be the tail of the previous one
+ foreach my $anagram (@acc) {
+ for (my $i = 0; $i <= length($anagram); $i++) {
+ push(@_, $anagram);
+ substr($_[-1], $i, 0) = $head;
+ }
+ }
+ goto &iter;
+ }
+ }
+ iter($_[0], (""));
+}
+
+for (@ARGV) {
+ for (anagrams($_)) {
+ print $_, "\n";
+ }
+}