Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Count replaces in search and replace

by VinsWorldcom (Parson)
on Mar 11, 2009 at 17:02 UTC ( #749952=perlquestion: print w/replies, xml ) Need Help??
VinsWorldcom has asked for the wisdom of the Perl Monks concerning the following question:

Using the line:

$_ =~ s/$replace/$map{$replace}/gi

to find $replace and replace it with the hash value of $map{$replace} case insensitive and all occurances on the given line works a treat.

However, I'd like to know 'how many' replacements were done on each line. Is there an easy way to get this value that I can increment in a counter to spit out at the end of the program that would say something like "Found and replaced X items"?

Replies are listed 'Best First'.
Re: Count replaces in search and replace
by kennethk (Abbot) on Mar 11, 2009 at 17:07 UTC

    In scalar context, substitution returns the number of replacements, i.e.

    $number = $_ =~ s/$replace/$map{$replace}/gi;

    See the documentation on substitution.
Re: Count replaces in search and replace
by ikegami (Pope) on Mar 11, 2009 at 17:56 UTC
    That kind of code is very susceptible to performance problems. Make sure you're not compiling $replace over and over again.
Re: Count replaces in search and replace
by VinsWorldcom (Parson) on Mar 12, 2009 at 14:30 UTC

    Thanks, the final solution I went with is:

    my $YESMapping = 0; foreach my $replace (keys(%map)) { $YESMapping = $YESMapping + ($_ =~ s/$replace/$map{$replace}/gi) } print "Replaced $YESMapping entries.\n"

    I did some reading on regex compiling and I'm looking at how to maybe apply that to the $replace variable which is obviously my loop index.

      One final comment - perhaps you should consider the += operator? As well, since you are visiting each key-value pair once, each might be appropriate. And, as long as you are using $_, you may way well use its shorthand.

      my $YESMapping = 0; while (my ($key, $value) = each %map) { $YESMapping += s/$key/$value/gi; } print "Replaced $YESMapping entries.\n"

        Yeah, I realized the += mistake (as in I should have used that) after I had posted it and saw it in front of me. I went back and changed my actual code.

        The "each" recommendation is new to me. I'm certainly not a Perl expert (yet), so I rely on the faithful "foreach" when I want to do something "for each" member of a group. Thanks for the tip, I'll read up on that and try it out.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://749952]
Approved by kennethk
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2017-08-22 00:19 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (326 votes). Check out past polls.