my @lastmatches; my $keep = 5; while ( my $line = ) { next unless $line =~ /criteria/; push @lastmatches, $line; unshift @lastmatches if --$keep < 1; } #### my @lastfive = ( grep { /criteria/ } ) [ -5 .. -1 ]; #### use strict; use warnings; # Create the 5mb file. my @alphabet = ( "A".."Z", "a".."z", " ", "\n"); open OUTFILE, ">file.txt" or die; print OUTFILE $alphabet[ rand( @alphabet) ] for 1 .. (1024 * 1024 * 5); close OUTFILE; # Find the last five occurrences of 'abc'. print "Testing grep method:\n"; open IN, "file.txt" or die; my @lastfive = ( grep { /abc/ } ) [-5 .. -1]; close IN; my $count = 5; print $count--, ".: ", $_ foreach @lastfive;