http://www.perlmonks.org?node_id=878979


in reply to Randomly regex substitute

Yet another solution (without claiming efficiency over previous solutions)

#!/usr/bin/perl -wl use strict; my $str = "boy boy girl boy girl boy girl girl"; my $l = int(rand(rindex($str,"boy") - 1)); $str =~ s/^(.{$l}.*?)\bboy\b/$1man/; print $str;
--
Regards
- Samar

Replies are listed 'Best First'.
Re^2: Randomly regex substitute
by oko1 (Deacon) on Dec 24, 2010 at 18:06 UTC

    Unfortunately, this one isn't very random - at least with regard to the first occurrence of 'boy'. I see where you tried to correct it with the '- 1', but that doesn't work:

    #!/usr/bin/perl -wl use strict; my %data; for (1..10000){ my $str = "boy boy girl boy girl boy girl girl"; my $l = int(rand(rindex($str,"boy") - 1)); $str =~ s/^(.{$l}.*?)\bboy\b/$1man/; $data{$str}++; } print "$_: $data{$_}" for sort keys %data;

    Output:

    boy boy girl boy girl man girl girl: 3323 boy boy girl man girl boy girl girl: 4310 boy man girl boy girl boy girl girl: 1881 man boy girl boy girl boy girl girl: 486

    (Don't ask me why I know about this problem. :)))


    --
    "Language shapes the way we think, and determines what we can think about."
    -- B. L. Whorf