faqts : Computers : Programming : Languages : Perl : Common Problems : File Handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

14 of 15 people (93%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How do I read the n'th line in a file?

Aug 31st, 2001 09:10
Tony Crosby, Per M Knutsen,


There are many ways of doing this, I would say for a beginner to use 
some methods like this.
open(data, "</path/to/file");
while(<data>){
if ($. == 9){
chomp;
$ninth_line=$_;
last;
}
}
close(data);
 And now your ninth line is in "$ninth_line",
 Here's another way,
open(data, "</path/to/data");
(@data)=<data>;
close(data);
print $data[8];
 $data[8] Would be the ninth line in this case since arrays start at 
zero.
 But considering that this method requires more memory and cpu power 
than the other, I'd use the previous method. For small databases 
however either would be ok, over 500 lines and I would say not to read 
a database into an array.
 Tony