summaryrefslogtreecommitdiff
path: root/005/ch1.pl
diff options
context:
space:
mode:
authorGuillermo Ramos2019-04-28 13:36:15 +0200
committerGuillermo Ramos2019-04-28 13:36:15 +0200
commitc0af731be7392e728b19091e40d69a183cf2db60 (patch)
tree61ef870721cc4c5e23e3e8af09af20a194d3f557 /005/ch1.pl
downloadperlweekly-c0af731be7392e728b19091e40d69a183cf2db60.tar.gz
005#1 (functional)
Diffstat (limited to '005/ch1.pl')
-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";
+ }
+}