Search code examples
perlfileiomultiprocessingtail

Tailing already opened file in Perl


I have one child process that writes into file some information dynamically. Sometimes I need to get N number of last lines of this file. But when parent process is reading file child will continue to write to it.
I have read that there is no sense to lock it and unlock, but I am not sure. I will not write anything from parent process, so I need to open it only for reading.
I have found module File::Tail , but didn't understand how to use it to get N number of last lines, please provide some simple example.

Also I need advice is it necessary to use locking in this case?


Solution

  • To read the last N lines of a files you can use the CPAN module File::ReadBackwards.

    use File::ReadBackwards;
    
    my $lastlines = File::ReadBackwards->new("file.txt");
    print reverse map { $lastlines->readline() } (1 .. 2);
    

    This will print last 2 lines of a file. Replace 2 with any number what you want.