waghso
waghso

Reputation: 595

blank substitute inside a substitution changes matched string to empty

I'm trying following piece of code. Basically this code should not be changing $data as per my understanding. Am I missing somethings? I'm using 5.22.3(strawberry perl).

use strict;
use warnings;
use 5.010;
my $data = 'we are here';
$data =~ s///g;
print "DATA1: $data\n";
$data =~ s{(we)}{
    my $x1 = $1;
    $x1 =~ s///g;
    print "x1: ^^$x1^^\n";
    "$x1"
}e;
print "DATA2: $data\n";

O/P-

DATA1: we are here
x1: ^^^^
DATA2:  are here

Upvotes: 1

Views: 77

Answers (1)

ikegami
ikegami

Reputation: 385829

Except when used by split, an empty pattern tells the match/substitute operator to use the last pattern to successfully match.

For example,

$ perl -e'$_ = "abba"; s//c/g if /a/ || /b/; CORE::say;'
cbbc

This means that

$x1 =~ s///g;

is equivalent to

$x1 =~ s/(we)//g;

To bypass that exception, you can use

$x1 =~ s/(?:)//g;

Say your real situation uses

$re = ...;
s/$re//g;

You could use

$re = ...;
s/(?:$re)//g;

or

$re = ...;
$re = qr/$re/;
s/$re//g;

Quote perlop,

The empty pattern //

If the PATTERN evaluates to the empty string, the last successfully matched regular expression is used instead. In this case, only the g and c flags on the empty pattern are honored; the other flags are taken from the original pattern. If no match has previously succeeded, this will (silently) act instead as a genuine empty pattern (which will always match).

Upvotes: 3

Related Questions