How can I read lines from the end of file in Perl?

后端 未结 11 1964
夕颜
夕颜 2020-12-06 02:41

I am working on a Perl script to read CSV file and do some calculations. CSV file has only two columns, something like below.

One Two
1.00 44.000
3.00 55.000         


        
11条回答
  •  余生分开走
    2020-12-06 03:23

    I've wrote quick backward file search using the following code on pure Perl:

    #!/usr/bin/perl 
    use warnings;
    use strict;
    my ($file, $num_of_lines) = @ARGV;
    
    my $count = 0;
    my $filesize = -s $file; # filesize used to control reaching the start of file while reading it backward
    my $offset = -2; # skip two last characters: \n and ^Z in the end of file
    
    open F, $file or die "Can't read $file: $!\n";
    
    while (abs($offset) < $filesize) {
        my $line = "";
        # we need to check the start of the file for seek in mode "2" 
        # as it continues to output data in revers order even when out of file range reached
        while (abs($offset) < $filesize) {
            seek F, $offset, 2;     # because of negative $offset & "2" - it will seek backward
            $offset -= 1;           # move back the counter
            my $char = getc F;
            last if $char eq "\n"; # catch the whole line if reached
            $line = $char . $line; # otherwise we have next character for current line
        }
    
        # got the next line!
        print $line, "\n";
    
        # exit the loop if we are done
        $count++;
        last if $count > $num_of_lines;
    }
    

    and run this script like:

    $ get-x-lines-from-end.pl ./myhugefile.log 200
    

提交回复
热议问题