Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Answer: How do I find the Nth occurrence of a pattern?

( #26398=categorized answer: print w/ replies, xml ) Need Help??

Q&A > regular expressions > How do I find the Nth occurrence of a pattern? contributed by Anonymous Monk

Here is a way to do this. This is more C than perl. I'd love for a monk to translate it. This defines a function that takes: the item to find, the teration to locate, an arry to search This returns the array index of the nth element. You get a -1 if none found.
@string = qw(34, 56, 78, 90, 98, 76, 54, 32, 10, 12, 13, 16, 19, 20, 1 +0, 56); sub nth_iter { my($item, $n, @list) = @_; $i = -1; $match = 0; $len = @list; while ($i++ < $len) { if($list[$i] == $item) { $match++; if ($match == $n) { last; } } } if ($match != $n) { $i = -1; } return $i; } print nth_iter(78, 1, @string);
Rock on! -Ty

Comment on Answer: How do I find the Nth occurrence of a pattern?
Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (14)
As of 2014-08-22 16:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (160 votes), past polls