http://qs1969.pair.com?node_id=1147587


in reply to Faster way to do this?

If you put the match in list context with (), it will return the matches which you can count and discard with a scalar context like this:
$count = () = /(M+)/g;

Replies are listed 'Best First'.
Re^2: Faster way to do this?
by stevieb (Canon) on Nov 12, 2015 at 16:39 UTC

    I thought that too, but it isn't faster:

    use warnings; use strict; use Benchmark qw(:all); open my $fh, '<', $ARGV[0] or die $!; cmpthese(100, { all => '_all', while => '_while', }); sub _all { seek $fh, 0, 0; my $count = 0; while (<$fh>){ $count += () = /(M+)/g; } # print "all: $count\n"; } sub _while { seek $fh, 0, 0; my $count=0; while(<$fh>){ while($_=~/(M+)/g){ $count++; } } # print "while: $count\n"; } __END__ Rate all while all 11.5/s -- -25% while 15.2/s 33% --