> ----Original Message----- > From: Umesh T G [mailto:[EMAIL PROTECTED] > > Sent: Friday, July 29, 2005 3:47 PM > To: beginners@perl.org > Subject: Read a single line in a file. > > > Hello List, > > I have a file with multiple lines. I want to read only the first line. > > and a particular word in that line. > > > For eg: > > File.txt > > apple,grape,orange,banana > some other lines > continued. > > So I want only the word grape here. How to get it? >
>From the cookbook, recipe 8.8 "Reading a Particular Line in a File" I use it and it works good. With this you can select any single line number, not just the first. You should be able to figure out how to extract a particular word from the line ---- # usage: build_index(*DATA_HANDLE, *INDEX_HANDLE) sub build_index { my $data_file = shift; my $index_file = shift; my $offset = 0; while (<$data_file>) { print $index_file pack("N", $offset); $offset = tell($data_file); } } # usage: line_with_index(*DATA_HANDLE, *INDEX_HANDLE, $LINE_NUMBER) # returns line or undef if LINE_NUMBER was out of range sub line_with_index { my $data_file = shift; my $index_file = shift; my $line_number = shift; my $size; # size of an index entry my $i_offset; # offset into the index of the entry my $entry; # index entry my $d_offset; # offset into the data file $size = length(pack("N", 0)); $i_offset = $size * ($line_number-1); seek($index_file, $i_offset, 0) or return; read($index_file, $entry, $size); $d_offset = unpack("N", $entry); seek($data_file, $d_offset, 0); return scalar(<$data_file>); } # usage: open(FILE, "< $file") or die "Can't open $file for reading: $!\n"; open(INDEX, "+>$file.idx") or die "Can't open $file.idx for read/write: $!\n"; build_index(*FILE, *INDEX); $line = line_with_index(*FILE, *INDEX, $seeking); -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>