use Algorithm::Combinatorics qw( combinations ); use Set::CrossProduct; my @base = split //, $str; for my $exact_distance ( 1 .. $d ) { my $change_idx_iter = combinations( [ 0 .. $#base ], $exact_distance ); while( my $change_idx = $change_idx_iter->next ) { my @base_combo = map { my $i = $_; [ grep { $base[ $i ] ne $_ } qw( A T C G ) ]; } @$change_idx; # HACK: Set::CrossProduct doesn’t work with a 1-dimensional matrix push @base_combo, [ 0 ] if $exact_distance == 1; my $bases_iter = Set::CrossProduct->new( \@base_combo ); my @neighbour = @base; while( my $new_bases = $bases_iter->get ) { @neighbour[ @$change_idx ] = @$new_bases; print @neighbour, "\n"; } } }