my @search_space; my $N = 100; foreach my $line () { # fill up @search_space with lines from FILE_B until it has N things # of course, this pukes when FILE_B reaches EOF ;) push(@search_space, ) while (@search_space < $N); # look for $line in @search_space my $pos = find(\@search_space, $line); if ($pos >= 0) { splice(@search_space, 0, $pos); # shift off the stuff in @search_space before the match } else { print "No match for $line"; } } sub find { my ($arr_ref, $find) = @_; $arr_ref->[$_] eq $find and return $_ for (0 .. $#{$arr_ref}); return -1; } #### 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"; } }