Earlier today I was searching the site for a way to emulate the UN*X tail command in Perl, specifically, tailing just the last line of a huge log file. I spent some time reading Simulating UNIX's "tail" in core Perl, and after some thought, I realize that for my specific application (and given who else might be maintaining the program now and in the future), that simply running the system tail command is probably the best way to go. Easy, fast - it's fine really.

I can't help wondering, though - just for educational reasons - what the most efficient way to get that last line is. I've got to think that while'ing through every line can't be right, especially for very large files. I'd think using seek might be better, so I put together a little program to seek backwards from the next-to-last character of the file to the first newline encountered, and print everything following. Here's what I've got:

use strict; open(FILE, $ARGV[0]) or die; my($i,$char); for ($i=-2;;$i--) { seek(FILE,$i,2) or exit; read(FILE,$char,1); $char eq "\n" and last; } while (<FILE>) { print; } close FILE;

This is my first encounter with seek (and my first post here), so I'm looking for feedback. Does this make sense? More efficient ways to do this? Pitfalls?

Thanks, Rob


In reply to tail -1 emulation efficiency by woodstea

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.