SPUG: Counting the number of instances in a string using Perl's regexes...

Daniel Chetlin daniel at chetlin.com
Mon Dec 18 14:55:01 CST 2000


On Mon, Dec 18, 2000 at 11:51:43AM -0800, Jonathan Gardner wrote:
> Say I had a string with a whole bunch of characters - "asdfjkhafjklhaf".
> 
> How would I go about counting the number of individual characters (say,
> 'a')?

Quickest and most idiomatic for counting a single character:

$string = "asdfjkhafjklhaf";            # => asdfjkhafjklhaf
$count = $string =~ tr/a//;             # => 3
$string;                                # => asdfjkhafjklhaf

(In other words, don't be afraid of tr/// -- it doesn't always modify
the string it operates on).

Most idiomatic for more than a single character:

$count = () = $string =~ /af/g;         # => 2

-dlc

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
  Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/





More information about the spug-list mailing list