Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

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

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

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

Here is my monkified version of the nth_iter subroutine. You gotta love map{}.
#!/usr/bin/perl -w my @string = (34, 56, 78, 90, 98, 76, 54, 32, 10, 12, 13, 16, 19, 20, +10, 56); sub nth_iter{ my ($item, $n, $list) = @_; ( map { $string[$_] == $item ? $_ : (); } 0..$#string )[--$n] or -1; } print nth_iter(78, 1, \@string);

Comment on Answer: How do I find the Nth occurrence of a pattern?
Download Code
Replies are listed 'Best First'.
RE: Answer: How do I find the Nth occurrence of a pattern?
by eak (Monk) on Aug 06, 2000 at 08:37 UTC
    I have to correct my code. I passed in a reference and never used it :(.
    #!/usr/bin/perl -w my @string = (34, 56, 78, 90, 98, 76, 54, 32, 10, 12, 13, 16, 19, 20, +10, 56); sub nth_iter{ my ($item, $n, $list) = @_; ( map { $list->[$_] == $item ? $_ : (); } 0..$#$list )[--$n] or -1 +; } print nth_iter(78, 1, \@string);
      Now using grep...speeed!!
      #!/usr/bin/perl -w my @string = (34, 56, 78, 90, 98, 76, 54, 32, 10, 12, 13, 16, 19, 20, +10, 56); sub nth_iter{ my ($item, $n, $list) = @_; ( grep $list->[$_] == $item, 0..$#$list )[--$n] or -1; } print nth_iter(10, 3, \@string);
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: (4)
As of 2015-07-28 02:33 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 (251 votes), past polls