#!/usr/bin/env perl
#
# tailz - simple program to read the last n line(s) of a file
# reads from the end of file for efficieny
#
# usage: tailz filename numberoflines
#
# ---
# source: https://github.com/trizen/perl-scripts

use strict;
use warnings;
use utf8;
use Encode         qw(decode_utf8);
use File::Basename qw(basename);

my $cmd_name = basename($0);
my $filename = shift or die "usage: $cmd_name [file] [numlines]\n";
my $numlines = shift // 10;
my $byte;

# Open the file in read mode
open my $fh, '<', $filename or die "Couldn't open $filename: $!";

# Rewind from the end of the file until count of eol 's
seek $fh, -1, 2;    # get past last eol
my $count = 0;

while ( tell($fh) > 0 ) {
    seek $fh, -1, 1;
    read $fh, $byte, 1;
    last if $byte eq "\n" and ++$count == $numlines;
    seek $fh, -1, 1;
}

local $/ = undef;
print scalar <$fh>;
