SPUG: Counting the number of instances in a string using Perl's regexes...
Colin Meyer
cmeyer at helvella.org
Mon Dec 18 15:59:06 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')?
$str = 'asdfjkhafjklhaf';
$num_a = $str =~ tr/a/a/;
from perldoc perlop:
tr/SEARCHLIST/REPLACEMENTLIST/cds
y/SEARCHLIST/REPLACEMENTLIST/cds
Transliterates all occurrences of the characters
found in the search list with the corresponding
character in the replacement list. *It returns the
number of characters replaced or deleted.* ...
also see perldoc perlfaq4 and search for:
How can I count the number of occurrences of a substring within a string?
-C.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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