in reply to How to run index on this one?

index returns an offset from the beginning of the string, although I'm not really sure what you mean by "false position". For example:
use strict; use warnings; my $string='YYSFTVMETDPVN[115]HMVGVISVEGRPGLFWFN[115]ISGGDK'; my $offset = 0; my $substring = 'N[115]'; my @positions; while (1) { my $pos = index($string, $substring, $offset); last if $pos < 0; push @positions,$pos; $offset = $pos + length($substring); } print "Positions: @positions\n";
Gives:
Positions: 12 35

Replies are listed 'Best First'.
Re^2: How to run index on this one?
by Anonymous Monk on Nov 25, 2009 at 15:23 UTC
    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.
      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.