regexperlspecial-variables

How can I find position of matched regex of a single string in Perl?


Let's say my $string = "XXXXXTPXXXXTPXXXXTP"; If I want to match: $string =~ /TP/; multiple times and return the position for each, how would I do so?

I have tried$-[0], $-[1], $-[2] but I only get a position for $-[0].

EDIT: I have also tried the global modifier //g and it still does not work.


Solution

  • $-[1] is the position of the text captured by the first capture. Your pattern has no captures.

    By calling //g in scalar context, only the next match is found, allowing you to grab the position of that match. Simply do this until you've found all the matches.

    while ($string =~ /TP/g) {
       say $-[0];
    }
    

    Of course, you could just as easily store them in a variable.

    my @positions;
    while ($string =~ /TP/g) {
       push @positions, $-[0];
    }