
Jasmine
Administrator
Mar 28, 2001, 2:44 PM
Post #4 of 8
(644 views)
|
Holding true to TIMTOWDI (there's more than one way to do it), another way to count occurances of something in a string is by using tr///, which probably the most efficient way to go. You can use any of the noted methods in a "normal" script, but if you're (let's say) counting the number of sentences in War and Peace, you'll probably want to use tr. Whenever in doubt on what's the most efficient way to do something in Perl, use the Benchmark module:
#!/usr/bin/perl use Benchmark; $count = 500_000; $string = 'Sentence 1. Sentence 2. Sentence 3.'; timethese($count, { 'split array' => sub { $count = @tokens = split( /\./, $string ); }, 'split into @_' => sub { $count = split( /\./, $string ); }, 'using tr' => sub { $count = ( $string =~ tr/\.// ); }, } ); Running this code outputs the following:
#output Benchmark: timing 500000 iterations of split array, split into @_, using tr... split array: 3 wallclock secs ( 2.03 usr + 0.00 sys = 2.03 CPU) split into @_: 1 wallclock secs ( 1.82 usr + 0.00 sys = 1.82 CPU) using tr: 0 wallclock secs ( 0.72 usr + 0.00 sys = 0.72 CPU) (note that split into @_ will give a warning that this is deprecated).
|