Tuff Contender
Tuff Contender

Reputation: 269

Is anything inside the string changed after binding operations?

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?

Upvotes: 4

Views: 80

Answers (1)

zdim
zdim

Reputation: 66883

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

Upvotes: 4

Related Questions