use strict; use warnings; use 5.014; use Benchmark qw{ cmpthese }; my $n = 4; my $str = q{x} x 50; substr $str, $_, 4, q{fred} for 4, 9, 20, 24, 31, 40; say qq{String: $str\n}; my $rcMovePos = sub { my $raMatches; while ( $str =~ m{\G(?:.{$n})*?(?=(fred.*))}g ) { push @{ $raMatches }, [ pos( $str ), $1 ]; pos $str += $n; } return $raMatches; }; my $rcNoDups = sub { my $rhMatches; $rhMatches->{ pos( $str ) } = $1 while $str =~ m{\G(?:.{$n})*?(?=(fred.*))}g; return $rhMatches; }; my $rcWithDups = sub { my $raMatches; push @{ $raMatches }, [ pos( $str ), $1 ] while $str =~ m{\G(?:.{$n})*?(?=(fred.*))}g; return $raMatches; }; my $raRes = $rcMovePos->(); say q{Using $rcMovePos}; say qq{ Matched $_->[ 1 ] at position $_->[ 0 ]} for @{ $raRes }; my $rhRes = $rcNoDups->(); say q{Using $rcNoDups}; say qq{ Matched $rhRes->{ $_ } at position $_} for sort { $a <=> $b } keys %{ $rhRes }; $raRes = $rcWithDups->(); say q{Using $rcWithDups}; say qq{ Matched $_->[ 1 ] at position $_->[ 0 ]} for @{ $raRes }; srand 1234567890; $str = q{x} x 10000; substr $str, int rand 9997, 4, q{fred} for 1 .. 50; say q{}; cmpthese( -5, { movePos => $rcMovePos, noDups => $rcNoDups, withDups => $rcWithDups, } );