http://www.perlmonks.org?node_id=1004038

kimmel has asked for the wisdom of the Perl Monks concerning the following question:

Okay I am trying to figure out why 'one' works but 'two' just hangs the script. I read perlre and perlretut again to see if the answer would just jump out at me and it didn't.

Edit: I forgot to paste part of the code below. See my follow-up comment for the correct full program.

#!/usr/bin/perl use v5.16; use warnings; use autodie qw( :all ); use utf8::all; use File::Slurp qw( read_file ); use Regexp::Assemble; use Benchmark qw( cmpthese :hireswallclock ); my %seen; my %seen2; my $fname = 'dracula.txt'; my $content = read_file($fname); $content =~ tr/!"#$%&'()*+,\-.\/:;<=>?@\[\\]^_`{|}~/ /; my @patterns = read_file('sample_patterns'); chomp @patterns; my $regex = join '|', map {quotemeta} @patterns; $regex = qr/\b($regex)\b/ixms; cmpthese( -5, { 'one' => sub { $seen{$1}++ while $content =~ /$regex/g; }, 'two' => sub { $seen2{$1}++ while $content =~ /$regex/; }, } );

The source text is Bram Stoker's Dracula a 836KB file with 16,248 lines. The sample_patterns file contains 4,000 patterns, one per line. The only difference between 'one' and 'two' is the g modifier on the regexp.