Read the last two lines, not the first two in Perl

I am trying to create a Perl script that outputs the last two lines of a file. My current script does what I want, except that it reads the first two lines, not the last two.

use strict;
use warnings;

my $file = 'test.txt';
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {   
    print $line;    
    last if $. == 2;
}

close $info;

What needs to be changed so that the script reads the last two lines, and not the first two?

+4
source share
2 answers

This is harder than printing the first lines! Here are a few options: from smallest to smartest:

Just use tail

Because who really needs a perl script to print the last two lines of a file?

Read all the lines from the file in the list and print the last two.

print do {
    open my $info, $file or die ...;
    (<$info>)[-2, -1];
};

Read all the lines from the file, just remembering the last two.

open my $info, $file or die ...;
my @lines;
while (my $line = <$info>) {
  shift @lines if @lines == 2;
  push @lines, $line;
}
print @lines;

, ; , .

, "" , . : File::ReadBackwards. :

use File::ReadBackwards;
my $info = File::ReadBackwards->new($file) or die ...;
my $last = $info->readline;
my $second_last = $info->readline;
print $second_last, $last;
+15

Tie::File File::ReadBackwards.

.

Tie::File

use strict;
use warnings;

use Tie::File;

my $file = 'test.txt';

tie my @file, 'Tie::File', $file or die $!;

print "\nUsing Tie::File\n";
print "$_\n" for @file[-2,-1];

File::ReadBackwards

use strict;
use warnings;

use File::Readbackwards;

my $file = 'test.txt';

my $backwards = File::ReadBackwards->new($file) or die $!;

my @last_two;
while (defined(my $line = $backwards->readline)) {
   unshift @last_two, $line;
   last if @last_two >= 2;
}

print "\nUsing File::ReadBackwards\n";
print @last_two;
+1

All Articles