open my $rndLines, '<', "rand_sorted.txt" or die "Can't open rand_sorted.txt: $!"; my %lines = map {$_ => undef} grep {chomp; length} <$rndLines>; close $rndLines; exists $lines{$.} and print while <>;