my $s = 'x';
print("\$s is $s,\$s =~ s///r is ",$s =~ s///r, ".\n");
$s =~ /x/;
print("\$s is $s,\$s =~ s///r is ",$s =~ s///r, ".\n");
prints
$s is x,$s =~ s///r is x.
$s is x,$s =~ s///r is .
So what is changed after the third line?
CodePudding user response:
Apparently, under /r modifier the substitution operator actually returns the rest of the original string from the position in the string after the last previous successful regex -- if the pattern was an empty string (and the string has not been changed)
perl -wE'$s = "x arest"; $s =~ /x a/; $r = ($s =~ s///r); say $s; say $r'
Prints the same $s, and then rest
It is the particular behavior with the empty-string pattern that affects this, per perlop
If the pattern evaluates to the empty string, the last successfully executed regular expression is used instead.
The way I see this to explain the behavior is that the // (empty string) pattern is literally replaced by the last match and
that is removed from the string, so the rest returned
perl -wE'$s = "x arest"; $s =~ /x a/; $r = ($s =~ s//X/r); say $r'
Prints Xrest.
Notes from hunting for a better understanding of this behavior, in case there is more to it than the above lone comment from perlop
It is not affected by
pos, as this works the same wayperl -wE'$s = "x arest"; $s =~ /x a/g; pos $s = 2; $r = ($s =~ s///r); say $r'I've added
/gso to be able to usepos. Just uses$&?The section on Repeated matches with zeo-length substring is clearly interesting in this regard, perhaps to explain the rationale for the behavior
