in reply to Reading Text Lines

seek() and tell() are what you need
# get the last $pos from somewhere my $pos = 0; open VIEWFILE, "< $path" or die "Can't open $path: $!<br>\n"; seek (VIEWFILE, $pos, 0) or die "Couldn't seek to $pos: $!<br>\n"; my $count = 100; while( defined(my $v_file = <VIEWFILE>) and $count--) { print "<div STYLE=\"font-family: 8pt Courier, 'Courier New', mon +ospace; font-size:.6em;\">$v_file</div><br>"; } # save $pos somewhere for the next page view $pos = tell(VIEWFILE); close VIEWFILE;
How you keep track of $pos and pass it from page to page is up to you.

Replies are listed 'Best First'.
Re^2: Reading Text Lines
by ikegami (Patriarch) on May 11, 2006 at 17:48 UTC
    I thought of that, but the problem with tell+seek is that you can't go backwards unless you keep track of all the previous positions. A hybrid solution would do the trick.
    my $max_lines = 100; open(my $fh, '<', $path) or die("Unable to open file $path: $!\n"); my $line = $cgi->param('line') || 0; my $pos = $cgi->param('pos'); if (defined($pos)) { seek($fh, $pos, 0) or die("Unable to seek to $pos: $!\n"); } else { if ($line) { do { <$fh> } while $. < $line; } } my $lines = $max_lines; print(qq{<div class="lines">\n}); while ($lines-- && defined(my $line = <$fh>)) { chomp($line); print(html_escape($line), qq{<br>\n}); } print(qq{</div>\n}); my $first = ($line == 0); my $last = not defined(<$fh>); my $prev_line = $line - $max_lines; $prev_line = 0 if $prev_line < 0; my $prev = "?line=$prev_line"; my $next_line = $line + ($max_lines - $lines) - 1; my $next_pos = tell($fh); my $next = "?line=$next_line&pos=$next_pos"; if ($first && $last) { print(qq{No other pages.<br>\n}); } else { print(qq{<a href="$prev">[prev page]</a> }) if !$first; print(qq{<a href="$next">[next page]</a> }) if !$last; print(qq{<br>\n}); }
Re^2: Reading Text Lines
by Anonymous Monk on May 11, 2006 at 17:25 UTC
    would I be able to reach the end of the file like that?
      As long as you save $pos after the run, and set it up again at the beginning of the next run, you'll continue to read through the file starting where you left off.

      In my example, $pos is set to 0, but in reality you would need to set it to the value it had after the last run. Setting it to 0 each time would continually read the first 100 lines over and over. You could pass it as a hidden form variable so when the user clicks 'next' they get the next 100 lines of file. You could also pass the previous $pos as a hidden form variable so the user gets the previous 100 lines of file when they click 'back'.
        I can't use a form, I have to pass the param. using a link. How could a upgrade the value of $pos?
        Ok, thanks I'm trying this.
        Actually I am trying to create a way to increment a variable to update $pos.