Update: Another solution:#!/usr/bin/perl -w use strict; my $line='boy boy girl boy girl boy girl girl'; my $count =()= $line =~ /boy/g; #number of boys on line print "number of boys = $count\n"; my $num = int(rand($count)) + 1; #1..$count print "looking for nth boy: $num\n"; my $found_position =-1; while ($num--) { $found_position= index($line,"boy", $found_position+1); print "replace index = $found_position\n"; } substr ($line, $found_position, length("boy"), "cowboy"); print "$line\n"; __END__ One example run: number of boys = 4 looking for nth boy: 3 replace index = 0 replace index = 4 replace index = 13 boy boy girl cowboy girl boy girl girl
oh, "Girly Boy" came about from an off hand comment from our out-going California Governor, Arnold Schwarzenegger - it became a bit of a joke, nothing was meant in any seriously derogatory way.#!/usr/bin/perl -w use strict; use Data::Dumper; my $line='boy boy girl boy girl boy girlyboy girl girl'; my @indicies; while ($line =~ /\bboy\b/gi) { push (@indicies, pos($line)-3); #pos is a bit tricky } print Dumper \@indicies; my $num = int(rand(@indicies)); #0..$count print "line = $line\n"; print "looking for nth boy: ",$num+1,"\n"; substr ($line, $indicies[$num], length("boy"), "cowboy"); print " $line\n"; __END__ Some runs: $VAR1 = [ 0, 4, 13, 22 ]; line = boy boy girl boy girl boy girlyboy girl girl looking for nth boy: 3 boy boy girl cowboy girl boy girlyboy girl girl ..... $VAR1 = [ 0, 4, 13, 22 ]; line = boy boy girl boy girl boy girlyboy girl girl looking for nth boy: 1 cowboy boy girl boy girl boy girlyboy girl girl ..... $VAR1 = [ 0, 4, 13, 22 ]; line = boy boy girl boy girl boy girlyboy girl girl looking for nth boy: 4 boy boy girl boy girl cowboy girlyboy girl girl
In reply to Re: Randomly regex substitute
by Marshall
in thread Randomly regex substitute
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |