#!/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; }