good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
Substitute (s///) a set of timesby jryan (Vicar) |
on Sep 03, 2004 at 22:14 UTC ( [id://388430]=CUFP: print w/replies, xml ) | Need Help?? |
This subroutine will s/// a set number of times. The obvious solution would seem to be: s/\Gpattern/blah/ while $count--, but that does not work because \G only works with m//, and s/(a)/<$1$1>/ while $count-- would restart the match each time at the beginning. (pos=0) Usage is: subtimes($string, $number_of_times, $pattern, $string_to_substitute). You can include $dollar variables in $string_to_substitute, just make sure to remember to backslash the dollar variable in the string. For instance, this: print subtimes("ababa", 2, qr/(a)/,"<\$1\$1>"); would print "<aa>b<aa>ba". Update: Fixed a bug.
Back to
Cool Uses for Perl
|
|