in reply to Re: How to run index on this one?
in thread How to run index on this one?

Thanks for the reply!
But, if you look at the string, I just want the position of 'N', without taking into consideration the [115] thing. In the code, you provided, it works ok for the first 'N', but for the second 'N', the correct position is 30 and not 35(this is because you count the first [115] and this increases the length of the string.

Replies are listed 'Best First'.
Re^3: How to run index on this one?
by cdarke (Prior) on Nov 25, 2009 at 15:31 UTC
    OK. I said I didn't understand what you meant! How about this then (damn the hard-coded 5):
    use strict; use warnings; my $string='YYSFTVMETDPVN[115]HMVGVISVEGRPGLFWFN[115]ISGGDKN[115]'; my $offset = 0; my $substring = 'N[115]'; my @positions; while (1) { my $pos = index($string, $substring, $offset); last if $pos < 0; $offset = $pos + length($substring); $pos -= 5 * @positions; push @positions,$pos; } print "Positions: @positions\n";
    Gives:
    Positions: 12 30 37
    I added another N for testing.

    Update:I have recieved a /msg puzzling about a line of code. Here is a description of $pos -= 5 * @positions;
    We need to adjust the position by the length of [115] (5 characters), not just just once but for each position found. I use @positions in scalar context to get me the number of elements (scalar context is forced by the multiplication operator *). The first time around the loop the number of elements in @positions is zero, so $pos is not decremented. Subsequently it is decremented by 5 * number-of-items-found.