SPUG: To sum it up... counting the number of occurences...
Scott Blachowicz
scott at sabmail.rresearch.com
Mon Dec 18 19:45:56 CST 2000
On Mon, Dec 18, 2000 at 02:52:36PM -0800, Jonathan Gardner wrote:
> To count the number of occurences of a rgex match in a string, I got the
> following suggestions:
>
> $count = $string =~ tr/a//; # From several of you...
>
> This works only if you are looking for individual characters. That isn't
> what I intended, but it was a very good solution to the example I posed. It
> is very fast, too. Trouble is that I never even think of using tr even when
> I should. It sits in the corner of my mind called "Perl Trivia" along with
> all the other stuff you can do but won't remember until someone else points
> out you should've.
>
> $count =0;
> $string =~ s/a/ ++$count , 'a' /eg; # Thanks to Jason Lampert
What about extending that one...
gator:~% cat ~/bin/charcount.pl
#! /usr/bin/perl
while (@ARGV) {
my $string = shift @ARGV;
%counts = ();
$string =~ s/([a-z])/++$counts{$1}, $1 /eg;
print "=== '$string' ===\n";
print map {"\t$_=$counts{$_}\n"} sort keys %counts;
}
gator:~% charcount.pl aldkfjasldfjasfjasldkjasdfjapirouerpowjfksdjfiaurpqej
=== 'aldkfjasldfjasfjasldkjasdfjapirouerpowjfksdjfiaurpqej' ===
a=7
d=5
e=2
f=6
i=2
j=8
k=3
l=3
o=2
p=3
q=1
r=3
s=5
u=2
w=1
Is that closer to the sort of thing you were looking for?
No idea how slow/fast it is...
--
Scott Blachowicz
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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