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
    Just curious, what if instead of replacing ONE boy, we are going to replace N boys? substr will definitely fail if the replacement string is of a different length?

      You replied to my post, but I think you intended to ask someone else this question — someone who used substr in his or her solution.

      My solution works with any arbitrary regular expression pattern and any arbitrary replacement string. I think my solution is the one most likely to earn the OP an A+.