Fun with Permutations

Ovid on 2005-01-15T06:42:34

use Data::Dumper;
use re 'eval';
my $string = "abcd";
my $regex = qr//;
my @perms;
$regex .= qr/(\G[abcd]{0,4}(?{push @perms => [$&,$']}))/ for 1 .. 4;
$string =~ $regex;
print Dumper \@perms;


Re:

Aristotle on 2005-01-15T22:57:19

Took me some staring and blinking until I noticed what the regex was doing with the \G but no /g despite a loop. This is clearer:

my $regex = qr/(\G[abcd]{0,4}(?{push @perms => [$&,$']}))/ x 4;

It might be personal bias that I hate doing string concatenations in a loop, but this seems to be a case where the x operator is a natural fit.

(Your final regex isn't precompiled, btw. I don't know if you are aware of that.)

I'm not sure the output I'm seeing either way is intended, though? It simply lists all possible ways to split this string, twice, but doesn't do what I'd expect when I hear “permutations.”