On Oct 23, Shannon Murdoch said:

>I've been using the while(<FILEHANDLE>){  command, but it's not very helpful
>when I need something on line #15 or something.
>
>Is there any function like $linecontents = line(FILEHANDLE,15);   ?

Make your own.  The concept uses a positional hash.  The hash looks like
this:

  %pos = (
    FILEHANDLE => [
      0,  # offset of line 1
      24, # offset of line 2
      70, # offset of line 3
    ],
  );

You'll see how this comes into play in a moment.

  my %pos;

  sub line {
    my ($fh, $line) = @_;

    # if we've worked with this filehandle before...
    if ($pos{$fh}) {
      # if we haven't recorded this line's position yet...
      while (@{ $pos{$fh} } < $line) {
        # go to the farthest line we've seen
        seek $fh, $pos{$fh}[-1], 0;

        # read a line
        <$fh>;

        # and push the position
        push @{ $pos{$fh} }, tell $fh;
      }

      # in any case, now position ourselves at the start of the line
      seek $fh, $pos{$fh}{$line-1}, 0;
    }

    # if we haven't seen this filehandle before...
    else {
      # go to the beginning of the file
      seek $fh, 0, 0;

      # line 1 has offset of 0
      push @{ $pos{$fh} }, tell $fh;

      # until we get to the line requested...
      for (2 .. $line) {
        # read a line
        <$fh>;

        # and push the position
        push @{ $pos{$fh} }, tell $fh;
      }
    }
  }

This code is used like so:

  open FILE, "< /path/to/file" or die "can't read /path/to/file: $!";
  line(\*FILE, 10);
  $line_10 = <FILE>;
  close FILE;

This process is relatively efficient.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to