Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitution with empty string: unexpected result

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>
like image 702
sid_com Avatar asked Oct 29 '12 09:10

sid_com


1 Answers

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.

like image 113
zoul Avatar answered Oct 26 '22 19:10

zoul