Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: search and replace plus counter

by hdb (Prior)
on Sep 20, 2013 at 10:48 UTC ( #1054999=note: print w/ replies, xml ) Need Help??


in reply to search and replace plus counter

The substitution operator returns the number of substitutions in scalar context, so you could write it like this:

use strict; use warnings; my @strings = qw/ one two three /; my $counter = 0; for ( @strings ) { $counter += s/o/O/; # only add one if s/// is successful } print "$counter replacements\n"; print "@strings\n"; $counter = 0; for ( @strings ) { $counter += s/e/E/g; # add number of replacements } print "$counter replacements\n"; print "@strings\n";

UPDATE: When you want to use the counter in your replacement string, then adding one should do the trick, not forgetting to remove it later:

use strict; use warnings; my @strings = qw/ one two three four /; my $counter = 1; for ( @strings ) { $counter += s/o/O$counter/; # only add one if s/// is successful } $counter--; print "$counter replacements\n"; print "@strings\n";


Comment on Re: search and replace plus counter
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1054999]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (15)
As of 2015-07-01 12:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What kind of chocolate gives you the most pleasure?















    Results (815 votes), past polls