use Algorithm::Permute; my $needle_chars = 'AAC'; my $haystack = 'AAACACAA'; my $p = Algorithm::Permute->new( [ split //, $needle_chars ], 3 ); my %perms; while( my @perm = $p->next ) { $perms{ join '', @perm }++; } my $pos = 0; while( $pos + 3 < length $haystack ) { my $pos_chars = substr $haystack, $pos, 3; print $pos_chars, " found at $pos\n" if exists $perms{ $pos_chars }; $pos++; }