Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
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 perusing the Monastery: (4)
As of 2014-12-27 01:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls