Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I have the string:
$string='LPNTGVTNNAYMPLLGIIGLVTSFSLLGLXKARRD';
I want to match R|K and find all occurences and their positions in the string.As you can see, I have 1 'K' and 2 'R'.
I use /g in my pattern matching ,but it only returns all letters. It gives me wrong positions however, when I use index to see the position of each one...
@matches=$string=~/(K|R)/g;<br> foreach $a(@matches) { print index($string, $a)."\n"; }
What am I doing wrong????

Replies are listed 'Best First'.
Re: match all instances?
by rhesa (Vicar) on May 27, 2006 at 15:53 UTC
    You're looking for the pos function:
    #!/usr/bin/perl my $string = 'LPNTGVTNNAYMPLLGIIGLVTSFSLLGLXKARRD'; while( $string =~ /([KR])/g ) { print "$1 at ", pos($string), $/; } __END__ K at 31 R at 33 R at 34
Re: match all instances?
by Zaxo (Archbishop) on May 27, 2006 at 15:59 UTC

    Your index function always starts from the beginning of the string, so at best has only two distinct values.

    You probably want the pos function and a while loop. Collecting an array of K's and R's is not getting you much. I'm going to rewrite the regex as a character class, though there's nothing wrong with yours.

    my $string = 'LPNTGVTNNAYMPLLGIIGLVTSFSLLGLXKARRD'; while ($string =~ /([KR])/g) { print pos($string) - length($1), $/; } __END__ 30 32 33

    After Compline,
    Zaxo

      Thank you very much!!! Problem solved
Re: match all instances?
by TedPride (Priest) on May 27, 2006 at 20:13 UTC
    $_ = 'LPNTGVTNNAYMPLLGIIGLVTSFSLLGLXKARRD'; print "$1: $-[0]\n" while m/([KR])/g;