windows下Perl如何讀取大檔案的最後一行(總結)

來源:互聯網
上載者:User

標籤:des   class   blog   http   ext   檔案   

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,$_);     [email protected]; } 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 -wuse strict;my $file = shift or die;my $content = "";open (F, $file) or die $!;seek (F, 0, 2);                                 # set handler at the end of $fileuntil ($content =~ m/\n(.*)\n?$/){        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/\n\n$/){        print "\n";}elsif ($content =~ m/\n?(.*)\n?$/){        print "$1\n";}else{        print $content, "\n";}

文中內容來自:提問http://bbs.chinaunix.net/thread-599099-1-1.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.