What does perl special variable $-[0] and $+[0] means
-
16-06-2021 - |
Domanda
I want to know the meaning of perl special variables $-[0]
and $+[0]
I have googled and found that $-
represent number of lines left on the page and $+
represent the last bracket matched by the last search pattern.
But my question is what $-[0]
and $+[0]
means in context of regular expressions.
Let me know if code sample is required.
Soluzione
See perldoc perlvar
about @+
and @-
.
$+[0]
is the offset into the string of the end of the entire match.
$-[0]
is the offset of the start of the last successful match.
Altri suggerimenti
These are both elements from an array (indicated by the square brackets and number), so you want to search for @- (the array) and not $- (an unrelated scalar variable).
The commend
perldoc perlvar
explains Perl's special variables. If you search in there for @- you will find.
$-[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
.
Adding example for better understanding of $-[0]
,$+[0]
Also adding info on variable $+
use strict;
use warnings;
my $str="This is a Hello World program";
$str=~/Hello/;
local $\="\n"; # Used to separate output
print $-[0]; # $-[0] is the offset of the start of the last successful match.
print $+[0]; # $+[0] is the offset into the string of the end of the entire match.
$str=~/(This)(.*?)Hello(.*?)program/;
print $str;
print $+; # This returns the last bracket result match
Output:
D:\perlex>perl perlvar.pl
10 # position of 'H' in str
15 # position where match ends in str
This is a Hello World program
World