Substitution with empty string: unexpected result

perl, string, substitution

Solution

Quote from man perlop:

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

Try to insert one successful regex match before the second substitution to see what’s going on:

(my $foo = '1') =~ s/1/x/; # successfully match “1”
$number =~ s///g;          # now you’re deleting all 1s
say "B: <$number>";        # <0000>

I’d say this should be deprecated and warned about by `use warnings`. It’s hard to see the benefits.

Problem

Why are the two printed numbers different? ``` #!/usr/bin/env perl use warnings; use 5.10.1; my $sep = ''; my $number = 110110110110111; $number =~ s/(\d)(?=(?:\d{3})+\b)/$1$sep/g; say "A: <$number>"; $number =~ s/\Q$sep\E//g; say "B: <$number>"; ``` Output: ``` A: <110110110110111> B: <11111111111> ```

Original source