Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is anything inside the string changed after binding operations?

Tags:

regex

perl

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?

like image 276
Tuff Contender Avatar asked Oct 17 '25 09:10

Tuff Contender


1 Answers

This is about the behavior with an empty-string pattern. Let's change the test a bit

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 when the pattern is an empty string that affects this, per perlop

If the pattern evaluates to the empty string, the last successfully executed regular expression is used instead.

Apparently the // (empty string) pattern is literally replaced by the last match, and that is removed from the string here; then under /r the rest returned

perl -wE'$s = "x arest"; $s =~ /x a/; $r = ($s =~ s//X/r); say $r'

Prints Xrest.

A few notes

  • This is not affected by pos, as this code works the same way

    perl -wE'$s = "x arest"; $s =~ /x a/g; pos $s = 1; $r = ($s =~ s///r); say $r'
    

    I've added /g so to be able to use pos. 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

like image 61
zdim Avatar answered Oct 19 '25 23:10

zdim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!