好吧,所以我注意到了perl中一些反直觀的grep行爲,具體取決於我打開文件的方式。如果我打開文件只讀,(<)它的工作。如果我打開它讀寫(+ <),它可以工作,但如果我打開它追加讀取,它不會。 (+ >>)Perl open()和grep
我相信這可以解決,但我很好奇它爲什麼這樣工作。任何人有一個很好的解釋?
給出一個test.txt
文件:
a
b
c
和greptest.pl
文件:
#!/usr/bin/perl
use strict;
use warnings;
open(RFILE, '<', "test.txt")
or die "Read failed: $!";
if(grep /b/, <RFILE>) {print "Found when opened read\n";}
else {print "Not found when opened read\n";}
close RFILE;
open(RWFILE, '+<', "test.txt")
or die "Write-read failed: $!";
if(grep /b/, <RWFILE>) {print "Found when opened write-read\n";}
else {print "Not found when opened write-read\n";}
close RWFILE;
open(AFILE, '+>>', "test.txt")
or die "Append-read failed: $!";
if(grep /b/, <AFILE>) {print "Found when opened append-read\n";}
else {print "Not found when opened append-read\n";}
close AFILE;
運行它返回以下內容:
$ ./greptest.pl
Found when opened read
Found when opened write-read
Not found when opened append-read
而我本來期望它找到在所有三個測試。
我最好的猜測是grep只從文件指針向前搜索,當你在追加文件中打開它時,文件指針被設置爲文件結尾。 – gcochard 2012-04-26 20:10:44
至少可以猜測。但爲什麼'+ <'與'+ >>'不同。都附加到文件的末尾。 – 2012-04-26 20:14:41