SPUG: Counting the number of instances in a string using Perl's regexes...
Jonathan Gardner
gardner at sounddomain.com
Mon Dec 18 13:51:43 CST 2000
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')?
One way I found in the book is this:
@arr = $string =~ m/a/g;
$number_of_a = scalar @arr;
Is there a more elegant way of going about this? I want to skip the creation
of @arr (I am worried about performance. The actual thing I will match is a
little big and will take some time to write to an array.) I have a gut
feeling that there is, and I just don't know what it is yet...
BTW, it's not:
$number = scalar $string =~ m/a/g;
or
$number = scalar ($string =~ m/a/g);
This use of scalar forces the function (m//) to return a scalar not an
array. It doesn't take the array we want so badly and count the number of
elements.
Jonathan M. Gardner
CarDomain Networks
(425)820-2244 x23
gardner at sounddomain.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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