Convert the position of a character in a string to account for "gaps" (i.e., non alphanumeric characters in the string)

Viewed 45

In a nutshell

I have a string that looks something like this ...

---MNTSDSEEDACNERTALVQSESPSLPSYTRQTDPQHGTTEPKRAGHT--------LARGGVAAPRERD

And I have a list of positions and corresponding characters that looks something like this...

position     character
10           A
12           N
53           V 
54           A

This position/character key doesn't account for hyphen (-) characters in the string. So for example, in the given string the first letter M is in position 1, the N in position 2, the T in position 3, etc. The T preceding the second chunk of hyphens is position 47, and the L after that hyphen chunk is position 48.

I need to convert the list of positions and corresponding characters so that the position accounts for hyphen characters. Something like this...

position     character
13           A
15           N
64           V 
65           A

I think there should be a simple enough way to do this, but I am fairly new so I am probably missing something obvious, sorry about that! I am doing this as part of bigger script, so if anyone had a way to accomplish this using perl that would be amazing. Thank you so much in advance and please let me know if I can clarify anything or provide more information!


What I tried

At first, I took a substring of characters equal to the position value, counted the number of hyphens in that substring, and added the hyphen count onto the original position. So for the first position/character in my list, take the first 10 characters, and then there are 3 hyphens in that substring, so 10+3 = 13 which gives the correct position. This works for most of my positions, but fails when the original position falls within a bunch of hyphens like for positions 53 and 54.

I also tried grabbing the character by taking out the hyphens and then using the original position value like this...

my @array = ($string =~ /\w/g);
my $character = $array[$position];

which worked great, but then I was having a hard time using this to convert the position to include the hyphens because there are too many matching characters to match the character I grabbed here back to the original string with hyphens and find the position in that (this may have been a dumb thing to try from the start).

1 Answers

The actual character seems not to be relevant. It's enough to count the non-hyphens:

use strict;
use warnings;
use Data::Dumper;
my $s = '---MNTSDSEEDACNERTALVQSESPSLPSYTRQTDPQHGTTEPKRAGHT--------LARGGVAAPRERD';
my @positions = (10,12,53,54);
my @transformed = ();
my $start = 0;

for my $loc(@positions){
    my $dist = $loc - $start;
    while ($dist){
        $dist-- if($s =~ m/[^-]/g);
    }
    my $pos = pos($s);
    push @transformed, $pos;
    $start = $loc;
}
print Dumper \@transformed;

prints:

$VAR1 = [
          13,
          15,
          64,
          65
        ];
Related