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