Perl print line example - How to print a specified line from a text file

Have you ever needed a program to print a specific line from a text file? I had this need a long time ago, and I wrote a Perl program to do just that, and I'd like to share it here.

There are certainly more Perl-ish ways to write a program to print a specific line from a text file, but hey, I don't use Perl that much these days, and I can still read this one. :)

Here's the source code for a Perl script I named perl-print-line.pl:

#!/usr/bin/perl

# purpose: print a specific line from a text file
# usage:   perl-print-line.pl line-number input-file

# use perl argv to verify the number of command line arguments
@ARGV == 2 or die "Usage: print-specific-line.pl line-number input-file\n";
$desired_line_number = $ARGV[0];
$filename = $ARGV[1];

# use perl open function to open the file (or die trying)
open(FILE, $filename) or die "Could not read from $filename, program halting.";

# loop through the file with a perl while loop, stopping when you get to the desired record
$count = 1;
while (<FILE>)
{
  if ($count == $desired_line_number)
  {
    # print line, then get out of here
    print $_;
    close FILE;
    exit;
  }
  $count++;
}
close FILE;

print "Sorry, I think the line number you entered is greater than the number of lines in the file.\n";

Example Perl print line program output

Okay, well there really isn't any exciting about the example output from this program, but to be clear, this is how I run this Perl script:

perl perl-print-line.pl 1000 my-long-file

The Perl way

If you really want to approach this problem "the Perl way", you'll probably want to look at the special Perl variable named $., but that's all I'll say about it. :) Sorry, but I'm not real big on memorizing special variables when I'm working with a half-dozen different programming languages.

 

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.