Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
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 lurking in the Monastery: (13)
As of 2015-07-29 20:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (268 votes), past polls