Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
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 drinking their drinks and smoking their pipes about the Monastery: (8)
As of 2014-09-23 22:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (241 votes), past polls