Jayesh Nair has asked for the wisdom of the Perl Monks concerning the following question:

monks, How can we go(read) to a specific line in a file? For example if i have to read the 15th line of the file.. Usually we can go only in a order starting from the first line,right.How can i directly raed a specific line? Help required urgently!!!!!!

Replies are listed 'Best First'.
Re: Going to a specific line in a file.
by ikegami (Patriarch) on Jun 13, 2007 at 14:13 UTC

    Tie::File still reads line by line, and has a lot of overhead. Alternative:

    do { die("Premature EOF") if not defined <FILE>; } while $. < 14; my $line15 = <FILE>;
Re: Going to a specific line in a file.
by marto (Cardinal) on Jun 13, 2007 at 14:04 UTC
Re: Going to a specific line in a file.
by citromatik (Curate) on Jun 13, 2007 at 14:05 UTC

    You can use the Tie::File module

    use strict; use warnings; use Tie::File; my $file = shift @ARGV; tie my @arr, 'Tie::File', $file; #Update: (thanks Corion and JohnGG) #print $arr[15]."\n"; print $arr[14]."\n";

    citromatik

      print $arr[15]."\n";

      <nit>That is the 16th line.</nit>

      Also, why not just interpolate into the string rather than using concatenation?

      print qq{$arr[14]\n};

      Cheers,

      JohnGG

Re: Going to a specific line in a file.
by fenLisesi (Priest) on Jun 13, 2007 at 14:01 UTC
    Unless your lines are of constant length, you have to go line by line. Cheers.
Re: Going to a specific line in a file.
by Anonymous Monk on Jun 13, 2007 at 19:38 UTC
    #!/usr/bin/perl open file,"./testFile.txt" or die; while (<file>) { next if (1..6); --> this skips the first 6 lines. print "$_\n"; }
Re: Going to a specific line in a file.
by ctilmes (Vicar) on Jun 14, 2007 at 11:28 UTC
Re: Going to a specific line in a file.
by Asmo (Monk) on Jun 14, 2007 at 20:56 UTC
    Simplest method :
    open (DATAFILE, $filename); @lines = <DATAFILE>; close(DATAFILE); print $lines[14];
A reply falls below the community's threshold of quality. You may see it by logging in.