in reply to Counting how many times a character is in a string.

Update: Nevermind, I was completely wrong here. Thanks to Aristotle for setting me straight. Apparently, I just breezed right over that section of the docs.

As has been mentioned several times, tr is the fastest and easiest way to get a count a particular character in a string. All of the examples up to this point have been destructive though. If you want to get a count without modifying the string, simply transliterate the character to itself.

my $str='abc%def%.%'; my $count = $str =~ tr/%/%/; print "\"$str\" has $count % in it.\n";

Replies are listed 'Best First'.
Re^2: Counting how many times a character is in a string.
by Aristotle (Chancellor) on Nov 18, 2005 at 18:21 UTC

    All of the examples up to this point have been destructive though.

    Wrong.

    Quoting perlop on tr:

    If the /d modifier is used, the REPLACEMENTLIST is always interpreted exactly as specified. Otherwise, if the REPLACEMENTLIST is shorter than the SEARCHLIST, the final character is replicated till it is long enough. If the REPLACEMENTLIST is empty, the SEARCHLIST is replicated. This latter is useful for counting characters in a class or for squashing character sequences in a class.

    (Underline mine.)

    Makeshifts last the longest.

      If the REPLACEMENTLIST is empty, the SEARCHLIST is replicated. This latter is useful for counting characters in a class
      Furthermore, this used to effectively replace characters by themselves, causing it to fail on read-only values, but that has been fixed. Now tr/%// merely counts.