#!/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