Tuesday, July 8, 2008

Print particular line/s from a file using perl

Method 1:

#!/usr/bin/perl

$filename = "test.csv";
open(INFILE, "<", $filename)
or die "Can't open $filename for reading: $!\n";

$line_number = 1;
while () {
$line = $_;
last if $. == $line_number;
}
if ($. != $line_number) {
die "Didn't find line $line_number in $filename\n";
}
print;

close(INFILE);



Method 2:

#!/usr/bin/perl

$filename = "test.csv";
open(INFILE, "<", $filename)
or die "Can't open $filename for reading: $!\n";
@lines = ;
$line1 = $lines[0];
$line2 = $lines[1];

print "$line1 \n";
print "$line2 \n";

close(INFILE);

No comments: