in reply to Randomly regex substitute
Here's an alternative way that uses three idioms from the Perl FAQ.
How can I count the number of occurrences of a substring within a string?
How do I get a random number between X and Y?
How do I change the Nth occurrence of something?
#!perl use strict; use warnings; use feature qw( say ); use English; my $line = 'boy boy girl boy girl boy girl girl'; say $line; my $match_pattern = qr/\bboy\b/; my $replacement_string = 'man'; my $total_matches = () = $line =~ m/$match_pattern/g; # Generate a random number from 1 to $total_matches... my $random_number = int(rand($total_matches)) + 1; my $match_number = 1; $line =~ s{ $match_pattern }{ $match_number++ == $random_number ? $replacement_string : $MATCH; }gex; say $line; exit 0;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Randomly regex substitute
by Anonymous Monk on Dec 24, 2010 at 07:23 UTC | |
by Jim (Curate) on Dec 24, 2010 at 07:52 UTC |