in reply to The nth occurrence of a character

Does no one use index() anymore?!?

#!/usr/bin/perl use warnings; use strict; sub find_nth { my ($s,$c,$n) = @_; my $pos = -1; while ($n--) { $pos = index($s,$c,$pos+1); return -1 if $pos == -1; } return $pos; } my $str="Now is the time for all good men to come to the aid of their +country"; my $n = 5; my $c = "o"; print find_nth($str,$c,$n), "\n";

I'll leave it to those people who like to benchmark to decide whether or not this is an "efficient Perl function" :-)

Replies are listed 'Best First'.
Re^2: The nth occurrence of a character
by duff (Parson) on Feb 09, 2006 at 06:07 UTC

    Ah well, in a fit of boredom I decided to benchmark the submissions myself. The results are unsurprising (at least to me).

    Here are some results on my system; the first set of benchmarks are for multple occurences in one string, the second set is for a single occurence in multiple strings:

                  Rate RoyJohnson      salva       duff    mickeyn
    RoyJohnson   373/s         --       -86%       -97%       -98%
    salva       2604/s       598%         --       -78%       -88%
    duff       11887/s      3089%       357%         --       -44%
    mickeyn    21159/s      5576%       713%        78%         --
                  Rate RoyJohnson      salva    mickeyn       duff
    RoyJohnson 15272/s         --        -9%       -42%       -48%
    salva      16847/s        10%         --       -36%       -42%
    mickeyn    26298/s        72%        56%         --       -10%
    duff       29202/s        91%        73%        11%         --