in reply to Counting SubStrings, Style Question

lanx@nc10-ubuntu:~$ perl -e ' $sub = "xxx"; $par = "xxx xxx xxx"; $count = () = $par =~ /$sub/g; $count == 0 ? print "none" : $count == 1 ? print "unique" : print "duplicates"; ' duplicates

HTH! :)

Cheers Rolf

UPDATE: beautified code ;)

see here how to avoid the ternary cascade.

Replies are listed 'Best First'.
Re^2: Counting SubStrings, Style Question
by AnomalousMonk (Archbishop) on Mar 20, 2010 at 20:58 UTC

    Although the OPed question does not seem to be concerned with overlapping occurrences, they can also be handled with m{pattern}g. If the sub-string may contain regex metacharacters, it is also wise to meta-quote.

    >perl -wMstrict -le "my $substring = 'xxx'; for my $string (@ARGV) { my $non_overlap =()= $string =~ m{ \Q$substring\E }xmsg; my $overlap =()= $string =~ m{ (?= (\Q$substring\E)) }xmsg; print qq{$non_overlap non-overlapping $substring in $string}; print qq{$overlap overlapping $substring in $string}; } " x xx xxx xxxx xxxxx xxxxxx 0 non-overlapping xxx in x 0 overlapping xxx in x 0 non-overlapping xxx in xx 0 overlapping xxx in xx 1 non-overlapping xxx in xxx 1 overlapping xxx in xxx 1 non-overlapping xxx in xxxx 2 overlapping xxx in xxxx 1 non-overlapping xxx in xxxxx 3 overlapping xxx in xxxxx 2 non-overlapping xxx in xxxxxx 4 overlapping xxx in xxxxxx

    Update: The capturing group in  m{ (?= (\Q$substring\E)) }xmsg is needed only if there is a concern with what matched rather than only with how many matched as in the OPed question.

      > If the sub-string may contain regex metacharacters, it is also wise to meta-quote.

      the same when using split.

      Cheers Rolf