1

So, let's say I am writing a Perl program:

./program.perl 10000 < file

I want it to read the 10000th line of "file" only. How could I do it using input redirection in this form? It seems that I keep getting something along the lines of 10000 is not a file.

I thought this would work:

#!/usr/bin/perl -w
$line_num = 0;
while ( defined ($line = <>) && $line_num < $ARGV[0]) {
    ++$line_no;
    if ($line_no == $ARGV[0]) {
        print "$line\n";
        exit 0;
    }
}

But it failed miserably.

1
  • Please use strict, as it would have caught your typo ($line_num vs. $line_no). Please also show us the error messages, as perl's complaint that it "Can't open 10000: No such file or directory..." is a good clue as to what else has gone wrong. Commented Jul 15, 2012 at 1:35

4 Answers 4

3

If there are command-line arguments, then <> opens the so-named files and reads from them, and if not, then it takes from standard-input. (See "I/O Operators" in the perlop man-page.)

If, as in your case, you want to read from standard-input whether or not there are command-line arguments, then you need to use <STDIN> instead:

while ( defined ($line = <STDIN>) && $line_num < $ARGV[0]) {
Sign up to request clarification or add additional context in comments.

1 Comment

@JordanCarney: You're welcome! By the way, I should also have mentioned -- you don't need to create your own $line_num variable; there's a predefined $. that does exactly this. (See the perlvar man-page.)
1

Obligatory one-liner:

perl -ne 'print if $. == 10000; exit if $. > 10000'

$. counts lines read from stdin. -n implicitly wraps program in:

while (<>) {
   ...program...
}

1 Comment

print and exit if $. == 10_000
1

You could use Tie::File

use Tie::File;
my ($name, $num) = @ARGV;
tie my @file, 'Tie::File', $name or die $!;

print $file[$num];
untie @file;

Usage:

perl script.pl file.csv 10000

Comments

0

You could also do this very simply using awk:

awk 'NR==10000' < file

or sed:

sed -n '10000p' file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.