It seems you could do this quite easily with grep if you are guaranteed that array2 will always be longer or larger than array1. Something like that:
sub align { my ($array1, $array2) = @_; my $index = 0; return grep { $array1->[$index] eq $array2->[$_] ? ++$index : 0 } 0 .. scalar( @$array2 ) - 1; }
Basically, grep says: "Return me a list of incrementing indices in array2, which correspond to adjacent elements from the array."
If you run the above using this test code, you will see that it returns the expected alignment array:
my @array1 = qw(ATCGTCGAGCG); my @array2 = qw(ACGTCCTGTCG); say join ",", align \@array1, \@array2;
This displays the expected display: 0.3,4,7,8,9,10. This list means that @array1[0 .. 6] matches @array2[0,3,4,7,8,9,10] .
(Note: you need to use Modern::Perl or similar to use say .)
Now you really haven't said what you need to output the operation. I suggested that you need this array of mappings. If you just need to count the number of elements skipped in @array2 when aligning with @array1 , you can still use the grep above, but instead of a list, just return scalar(@$array2) - $index at the end.
source share