zoukankan      html  css  js  c++  java
  • windows下Perl如何读取大文件的最后一行(总结)

    Perl中读取文件最后一行的方法很多,比如

    (1)将文件读入数组,取最后一个元素

    open (FILE,"file.txt") or die "$!";
    my @arr=<FILE>;;
    close FILE;
    my $last=$arr[$#arr];
    
    #$last里就是最后一行的内容了。
    

    (2)一行一行读入,到最后一行时输出

    open (FILE,"file.txt") or die "$!";
    while (<FILE>;)
    {
        open (TMP,">tmp.txt") or die "$!";
        print TMP $_;
        close TMP;
    }
    close FILE;
    

    或者

    open (FILE,"file.txt") ; 
    $a=<FILE>;;push(@a,$a); 
    while (<FILE> )
    {
         push(@a,$_); 
        shift@a; 
    } 
    close FILE; 
    print @a;
    

    (3)这个并未尝试过,有兴趣可以试试

    http://search.cpan.org/~mjd/Tie-File-0.96/lib/Tie/File.pm
    DESCRIPTION ^

    Tie::File represents a regular text file as a Perl array. Each element in the array corresponds to a record in the file. The first line of the file is element 0 of the array; the second line is element 1, and so on.

    The file is not loaded into memory, so this will work even for gigantic files.

    Changes to the array are reflected in the file immediately.

    Lazy people and beginners may now stop reading the manual.

    (4)以上的方法都需要遍历整个文件,效率较低。下面这个方法是最高效的,特别是文件很大时,方法是:  

      打开文件,把指针移动到最后面,一个一个字节往前读,直到读到N为止

    #!/usr/bin/perl -w
    
    use strict;
    
    my $file = shift or die;
    my $content = "";
    
    open (F, $file) or die $!;
    seek (F, 0, 2);                                 # set handler at the end of $file
    until ($content =~ m/
    (.*)
    ?$/)
    {
            my $string;
            if (seek (F, -1024, 1))              # backward 1024 bytes
            {
                    my $n = read (F, $string, 1024) or die $!;
                    $content = $string . $content;
                    last if ($n < 1024);
                    seek(F, -1024, 1);
            }
            else{
                    my $len = tell F;
                    seek (F, 0, 0) || die "see error at $file";
                    read (F, $string, $len) or die $!;
                    $content = $string . $content;
                    last;
            }
    }
    close(F);
    
    if ($content =~ m/
    
    $/)
    {
            print "
    ";
    }elsif ($content =~ m/
    ?(.*)
    ?$/){
            print "$1
    ";
    }else{
            print $content, "
    ";
    }
    

    文中内容来自:提问http://bbs.chinaunix.net/thread-599099-1-1.html

  • 相关阅读:
    计算机基础--http的基础整理和巩固
    设计方案系列-如何看待前端框架选型 ?
    数据可视化-svg入门基础(二)
    数据可视化系列--svg入门基础(一)
    Jenkins自动部署增加http状态码校验
    快速搭建python程序
    Request 接收参数乱码原理解析三:实例分析
    Request 接收参数乱码原理解析二:浏览器端编码原理
    Request 接收参数乱码原理解析一:服务器端解码原理
    Newtonsoft.Json(Json.Net)学习笔记
  • 原文地址:https://www.cnblogs.com/Gihub/p/3807248.html
Copyright © 2011-2022 走看看