Håkon Hægland
Håkon Hægland

Reputation: 40718

Matching a zero with String::Substitution

I am trying to match a digit with String::Substitution; it works fine if the digit is not zero. If the digit is zero it substitutes the empty string instead of the digit. For example:

use strict;
use warnings;

use Data::Dump;
use String::Substitution;

my @data = qw(0 1);
for (@data) {
    my $str = $_;
    my $regex = qr/(\d)/;
    my $replace = '$1';
    my $result_str = String::Substitution::gsub_copy($str, $regex, $replace);
    my @m = $str =~ /$regex/g;
    dd $result_str;
    dd @m;
}

The output is:

""
0
1
1

expected output would be:

0
0
1
1

Upvotes: 2

Views: 54

Answers (1)

ikegami
ikegami

Reputation: 385645

To avoid "uninitialized" warnings, version 1.001 of the module attempts to convert undefined placeholders into empty strings. However, it erroneously uses a truth test rather an defined test to determine which values to replace with an empty string.

map { ($$_) || '' } ( 1 .. $#- )

That code needs to be changed to

map { defined($$_) ? $$_ : '' } ( 1 .. $#- )

A bug report has been submitted.

Upvotes: 1

Related Questions