my %lines_of_interest = map { $_ => 1 } 6, 1003, 2965; open my $fh, '<', $file_name or die("Unable to open file \"$file_name\": $!\n"); my $num_lines = keys %lines_of_interest; while (<$fh>) { if ($lines_of_interest{$.}) { print; last unless --$num_lines; } }