Tweet

How do I read a file backwards?

The problem

You want to read a file, for example a log file, starting at the last line and progressing towards the first line. It may be a large file so you do not want to read it all in to memory first.

The solution

Use the File::ReadBackwards module. This module is very simple to use and does exactly what you expect.

If you had a file called backwards.txt, that contained the following data:

    aa
    bb
    cc
    dd
    ee

And you ran the following script:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use File::ReadBackwards;

    my $bw = File::ReadBackwards->new("backwards.txt") or die $!;

    my $line;
    while (defined($line = $bw->readline)) {
        print $line;
    }

    $bw->close();

The output you would see would be:

    ee
    dd
    cc
    bb
    aa

See Also

    perldoc File::ReadBackwards
Revision: 1.5 [Top]