cherio cherio - 9 months ago 40
Perl Question

Perl regex variable for replacement count

For a simple use case as this one

#!/usr/bin/perl
my $text = "A choice between ASCII and UTF8 is simple";
$text =~ s/[[:upper:]]+/?/g;


I need to determine if a replacement was made or not. I am hoping to find a built in variable which would tell me that. It seems like there are lot's of variables available related to regex (e.g. $1, ... $', $&, @+, @- etc) but I haven't find one that can simply tell me whether a replacement was made or not or number of replacements made etc.

Sure I can save the original string and compare with the result though if this statistics is already available in one way or another I'd use it.

Answer Source

The s/// operator (without the /r flag) returns the number of replacements done, so you can simply do

if ($text =~ s/[[:upper:]]+/?/g) {
    # at least one replacement was done
} else {
    # nothing changed
}