use Tie::File; use Fcntl 'O_RDONLY'; my @array; tie @array, 'Tie::File', $ARGV[0], mode => O_RDONLY or die; foreach my $i ( 0 .. $#array ){ # no, doesn't handle index edge case of $i < 4 print join "", @array[$i-4,$i-1] if $array[$i] =~ /foo/; }