SPUG: Counting the number of instances in a string using Perl's
regexes...
Joel Grow
largest at largest.org
Mon Dec 18 14:24:32 CST 2000
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')?
Here's 2 ways. If you're unfamiliar with the tr operator, see pages
155-157 of the new Camel for an explanation of transliteration.
my $count;
$count++ while ( $string =~ /a/g );
# Or,
my $count = ($string =~ tr/a/a/);
Joel
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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