in reply to search for nth occurrence of a pattern in a line
# $n is the nth wanted occurence, as indicated by the question. # $i holds how many times we found the pattern my $str = ',n ,pple , d,y'; my ($n, $i) = 4; $str =~ / , # we are searching for the , pattern (?{ $i++}) # we found it again , increament $i /xgc # retain last occurance on failure for (1..$n); # print position in string print +($n == $i) ? pos($str) - 1 : 'not found';
|
|---|