in reply to search for nth occurrence of a pattern in a line

use strict; use warnings; my ($str, $nth, $p); $str = "dsf,sdg,hjhgj,gjkh"; $p = -1; $nth = 3; while ($str =~ /,/g) { $p = pos($str) - length($&), last if !--$nth; } print substr($str, $p) if $p != -1;
Regex is better imho, since you don't know if you might want to do a pattern match some time in the future.

Replies are listed 'Best First'.
Re^2: search for nth occurrence of a pattern in a line
by japhy (Canon) on May 17, 2006 at 20:09 UTC
    pos($str) - length($&)? Ewwww. First of all, $& is a Curse, and second, you can just use $-[0] to get the same location.
    while ($str =~ /,/g) { $p = $-[0], last if !--$nth }

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart