in reply to Counting SubStrings, Style Question

You can also use the simple:
my $count = 0; ++$count while ( $parent =~ /$substring/go );

...which is faster and uses less memory in my benchmarks than the =()= "operator". I also find it more readable.

Another reason split is bad: If the string ends with the substring you get 1 less in split's result.

mclapdawg:829841 juster$ perl -E 'say scalar split /xxx/, q{xxx xxx }' 3 mclapdawg:829841 juster$ perl -E 'say scalar split /xxx/, q{xxx xxx}' 2

Replies are listed 'Best First'.
Re^2: Counting SubStrings, Style Question
by LanX (Saint) on Mar 21, 2010 at 10:48 UTC
    > Another reason split is bad: If the string ends with the substring you get 1 less in split's result.

    May I correct you?

    Split isn't "bad" it's wrong!

    Excellent, the best reason so far! =)

    > I also find it more readable.

    Well ... readability is a question of taste and habit. And this approach needs to always initialize $count with 0.

    But IMHO the o modifier is quite pointless here not really necessary anymore and doesn't make it more readable. :)

    > ...which is faster and uses less memory in my benchmarks than the =()= "operator".

    I got a penalty between 50 and 100% which is not sooo dramatic... and this highly depends on the length of the investigated string!

    So the question is rather, if searching for millions of matches is really a common use case of the OP.

    Cheers Rolf