perlregex

Perl - positions of regex match in string


if (my @matches = $input_string =~ /$metadata[$_]{"pattern"}/g) {
  print $-[1] . "\n"; # this gives me error uninitialized ...
}

print scalar @matches; gaves me 4, that is ok, but if i use $-[1] to get start of first match, it gaves me error. Where is problem?

EDIT1: How i can get positions of each match in string? If i have string "ahoj ahoj ahoj" and regexp /ahoj/g, how i can get positions of start and end of each "ahoj" in string?


Solution

  • The array @- contains the offset of the start of the last successful match (in $-[0]) and the offset of any captures there may have been in that match (in $-[1], $-[2] etc.).

    There are no captures in your string, so only $-[0] is valid, and (in your case) the last successful match is the fourth one, so it will contain the offset of the fourth instance of the pattern.

    The way to get the offsets of individual matches is to write

    my @matches;
    while ("ahoj ahoj ahoj" =~ /(ahoj)/g) {
      push @matches, $1;
      print $-[0], "\n";
    }
    

    output

    0
    5
    10
    

    Or if you don't want the individual matched strings, then

    my @matches;
    push @matches, $-[0] while "ahoj ahoj ahoj" =~ /ahoj/g;