@-
$-[0] is the offset of the start of the last successful match. $-[n] is the offset of the start of the substring matched by n-th subpattern, or undef if the subpattern did not match.
Thus after a match against $_, $& coincides with substr $_, $-[0], $+[0] - $-[0]. Similarly, $n coincides with substr $_, $-[n], $+[n] - $-[n] if $-[n] is defined, and $+ coincides with substr $_, $-[$#-], $+[$#-]. One can use $#- to find the last matched subgroup in the last successful match. Contrast with $#+, the number of subgroups in the regular expression. Compare with @+.
This array holds the offsets of the beginnings of the last successful submatches in the currently active dynamic scope. $-[0] is the offset into the string of the beginning of the entire match. The nth element of this array holds the offset of the nth submatch, so $+[1] is the offset where $1 begins, $+[2] the offset where $2 begins, and so on. You can use $#- to determine how many subgroups were in the last successful match. Compare with the @+ variable.
After a match against some variable $var:
$` is the same as substr($var, 0, $-[0]) $& is the same as substr($var, $-[0], $+[0] - $-[0]) $' is the same as substr($var, $+[0]) $1 is the same as substr($var, $-[1], $+[1] - $-[1]) $2 is the same as substr($var, $-[2], $+[2] - $-[2]) $3 is the same as substr $var, $-[3], $+[3] - $-[3])
Therefore, you can do something like this:
I don't know if this method incurs the same overhead as $`, etc... anybody?my $q = <<End_Text; some_letters-01-some_other_letters some_other_letters-03-some_other_letters End_Text while ( $q =~ m{\w+ \-(\d\d)\- \w* }gx ) { my $start_index = $-[1]; print "Mask start index is ", $start_index, "\n"; }
Update: The previous code made loud banging sounds when tested. This code fixes it. Works on 5.6; uncertain if it will work for previous Perls.
stephen
In reply to Re: Using index when the substring as is a regular expression
by stephen
in thread Using index when the substring as is a regular expression
by rbi
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |