Here's an alternative way to do it.

The function last_n_lines takes 3 arguments:  the filename, the number of lines N to read from the end, and an optional maximum line length.  It then returns a reference to an array containing the last N lines from the file.  It will work especially well on very huge files, as it doesn't read all of the lines into memory first:

#!/usr/bin/perl -w + # Strict use strict; use warnings; + # User-defined my $n = 3; # How many lines to read from the end my $file = "/usr/dict/words"; # File to read + + # Main program my $plines = last_n_lines($file, $n, 256); print "Last $n line(s) from '$file':\n"; for (my $i = 0; $i < @$plines; $i++) { printf " %2d. '%s'\n", $i+1, $plines->[$i]; } + + # # In: $1 ... name of file # $2 ... number of lines to read # $3 ... (optional) maximum line length # # Out: $1 ... pointer to list of the last N lines from the file. # sub last_n_lines { my ($fname, $nlines, $maxlen) = @_; + # Open the file open(my $fh, "<", $file) or die "Error -- failed to read '$fname' +($!)\n"; + # Calculate offset near end of file $maxlen ||= 1024; my $offset = (-s $file) - ($maxlen + 1) * $nlines; ($offset > 0) and seek($fh, $offset, 0); + # Read lines my @lines; while (!eof($fh)) { chomp(my $line = <$fh>); push @lines, $line; } + # Return last N close $fh; splice(@lines, 0, -$nlines); return \@lines; }

Update:  Removed a line which I just realized I had put in during testing of the program.


s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

In reply to Re: how can i read only the last line of a files by liverpole
in thread how can i read only the last line of a files by Anonymous Monk

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.