SPUG: Counting the number of instances in a string using Perl 's regexes...

Lauren Smith LaurenS at bsquare.com
Mon Dec 18 15:14:22 CST 2000


> >
> > 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/);

A quick benchmark:

c:\>perl
use Benchmark;
$string = 'asdfljkblj;asdflj;a;ljkas;ldfasljf;';
timethese(1000000,
        { trans => sub { $count = ($string =~ tr/a/a/); },
          regex => sub { $count++ while ($string =~ /a/g); }
        }
);
^Z
Benchmark: timing 1000000 iterations of regex, trans...
     regex:  5 wallclock secs ( 5.92 usr +  0.00 sys =  5.92 CPU) @
168976.01/s (n=1000000)
     trans:  0 wallclock secs ( 1.33 usr +  0.00 sys =  1.33 CPU) @
750750.75/s (n=1000000)

Lauren Smith
-- 
eVT Maintenance
(425) 519-5253


 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     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