#!/usr/bin/perl use strict; use warnings; use Benchmark::Forking qw( timethese cmpthese ); # UnixOS # use Benchmark qw(:all) ; # WindowsOS sub test_grep { my @matched = grep { $_ =~ /AGGT/ } <>; if (@matched) { for(@matched) { chomp $_; print "Grep: " . length($_) . "\n";} } close ARGV if eof; } sub test_while { my $count; while (<>) { if ($_ =~ /^>hsa/){ chomp (my $line = <>); $count .= length($line); $count .= " "; } } continue { close ARGV if eof; # reset $. each file } print "While: " . $count . "\n"; } # test_grep(); # Works fine separate but not combined test_while(); # Works fine separate but not combined __DATA__ $ perl test.pl test.txt Grep: 107 Grep: 251 ^C $ perl test.pl test.txt While: 107 251 ^C __END__ my $results = timethese( 2, { 'Grep' => sub { }, 'While' => sub { }, }, 'none' ); cmpthese( $results ); #### >hsa_circ_0000001|chr1:1080738-1080845-|None|None ATGGGGTTGGGTCAGCCGTGCGGTCAGGTCAGGTCGGCCATGAGGTCAGGTGGGGTCGGCCATGAAGGTGGTGGGGGTCATGAGGTCACAAGGGGGTCGGCCATGTG >hsa_circ_0000002|chr1:1158623-1159348-|NM_016176|SDF4 GGTGGATGTGAACACTGACCGGAAGATCAGTGCCAAGGAGATGCAGCGCTGGATCATGGAGAAGACGGCCGAGCACTTCCAGGAGGCCATGGAGGAGAGCAAGACACACTTCCGCGCCGTGGACCCTGACGGGGACGGTCACGTGTCTTGGGACGAGTATAAGGTGAAGTTTTTGGCGAGTAAAGGCCATAGCGAGAAGGAGGTTGCCGACGCCATCAGGCTCAACGAGGAACTCAAAGTGGATGAGGAAA #### #!/usr/bin/perl use strict; use warnings; use Benchmark::Forking qw( timethese cmpthese ); # UnixOS # use Benchmark qw(:all) ; # WindowsOS my @preserved = @ARGV; sub test_grep { @ARGV = @preserved; # restore original @ARGV my @matched = grep { $_ =~ /AGGT/ } <>; my $count; if (@matched) { for(@matched) { chomp $_; $count .= length($_) . " ";} } close ARGV if eof; } sub test_while { @ARGV = @preserved; # restore original @ARGV my $count; while (<>) { if ($_ =~ /AGGT/){ chomp; $count .= length($_) . " "; } } continue { close ARGV if eof; # reset $. each file } } my $results = timethese(10000000, { Grep => \&test_grep, While => \&test_while }, 'none'); cmpthese( $results ); __DATA__ perl test.pl test.txt Rate Grep While Grep 144175/s -- -21% While 182882/s 27% --