my $N = 100; my @file_b; tie @file_b, Tie::File, 'path/to/file_b' or die; my $last_match = 0; for my $line () { chomp $line; my $min = $last_match - $N >= 0 ? $last_match - $N : 0; my $max = $last_match + $N <= $#file_b ? $last_match + $N : $#file_b; my $pos = find(\@file_b[$min .. $max], $line); if ($pos >= 0) { $last_match = $min + $pos; } else { print "No match for $line\n"; } }