sub genRegex{ my $word = shift; my $re = '(.)'; my @c = split '', $word ; for my $c ( 1 .. $#c ) { my $match = 1+index $word, $c[$i], 0; $re .= $match <= $c[$i] ? '($' . ($match - 1) . ')' : '([^$' . join( '$', 1..$i ) . '])'; } } return qr[$re]; } ... # Build a hash relating cryptoword with a regex to find possible matches. $soln{$_}{regex} = genRegex $_ for @crypts; open WORDS, ' ) ) { print $word; for( keys %soln ) { push @{ $soln{ $_ }{ possibles } }, $word if $word =~ $soln{$_}{regex}; } }