SPUG: Re: Counting the number of instances in a string using Perl's
Aaron Fossum
fossumar at hotmail.com
Mon Dec 18 14:25:20 CST 2000
I think there's a recipe for this in the Perl Cookbook, but my copy's not handy here. :)
while( $string =~ /yourstringhere/g ) {
$count++;
}
should work.
Cheers!
Aaron Fossum
bCentral.com
----- Original Message -----
From: Jonathan Gardner
Sent: Monday, December 18, 2000 12:02 PM
To: spug-list at pm.org
Subject: SPUG: Counting the number of instances in a string using Perl's
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/<br clear=all><hr>Get your FREE download of MSN Explorer at <a href="http://explorer.msn.com">http://explorer.msn.com</a><br></p>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/archives/spug-list/attachments/20001218/5f45affe/attachment.htm
More information about the spug-list
mailing list