Get specific lines from a huge text file I had a 50 Gb text file (ca. 45 mln lines) and needed to extract about 1500 lines from it. I knew their indices, that is, line numbers. Those 1500 lines were spread across the whole file up to the very end. To accomplish this, I wrote a simple Perl script. It worked and was quite fast: it finished in about 4-5 minutes on a low-end "business" laptop (but with an SSD).  

Question 1: Is the code sensible and well-written?
Question 2: Could the performance be improved somehow?

#!/bin/perl
# 
# Get lines from a file using line numbers from a second file
# Syntax
# getlinesfromfile.pl &lt;source-file&gt; &lt;index-file&gt; &lt;output-file&gt;
#
# Index file contains line numbers, one per line
# Example:
#
# 1
# 5
# 17
# 73
# 31337

use strict;
use warnings;

my $version = "1.0.4";
my $date_released = "4 December 2019";
print "\nGet lines from file. Version $version released on $date_released\n";

my ($source_file, $idx_file, $output_file) = @ARGV;
if (not defined $source_file or not defined $output_file or not defined $idx_file) {
    print "Parameters missing. Usage:\n\t$0 &lt;source_file&gt; &lt;idx_file&gt; &lt;output_file&gt;";
    exit;
}

open(my $i_fh, '&lt;', $source_file)
    or die "FAILED to open '$source_file'!";
open(my $idx_fh, '&lt;', $idx_file)
    or die "FAILED to open '$idx_file'!";
open(my $o_fh, '&gt;', $output_file)
    or die "FAILED to open '$output_file'!";

# Read in indices
$/ = "\r\n";
my %indices;
while (my $line = &lt;$idx_fh&gt;) {
    chomp $line;
    $indices{$line} = 1;
}
close $idx_fh;
my $count_indices = scalar keys %indices;

my $msg_intro = &lt;&lt;"END";
Input filename: '$source_file'
Index filename: '$idx_file'
Output filename: '$output_file'

Indices: $count_indices

END

print $msg_intro;

my $lines_found = 0;
my $lines_parsed = 0;
$/ = "\n";
while (my $line = &lt;$i_fh&gt;) {
    chomp $line;
    $lines_parsed++;
    if (defined $indices{$lines_parsed}) {
        print $o_fh $line, "\r\n";
        $lines_found++;
    }
}
close $o_fh;
close $i_fh;
print ("Parsed $lines_parsed lines, found $lines_found matches.\n");
I know this might be a one time task, however, if you want to create a reusable code, I would always put the line counting code in a "continue" block. It is more readable and safer for future enhancements. Somehow the line increment code "finds itself" pushed after a next statement...

while (my $line = &lt;$i_fh&gt;) {
    chomp $line;
    if (defined $indices{$lines_parsed}) {
        print $o_fh $line, "\r\n";
        $lines_found++;
    }
} continue {
    $lines_parsed++;
}