2012-04-26 60 views
1

好吧,所以我注意到了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 

而我本來期望它找到在所有三個測試。

+0

我最好的猜測是grep只從文件指針向前搜索,當你在追加文件中打開它時,文件指針被設置爲文件結尾。 – gcochard 2012-04-26 20:10:44

+0

至少可以猜測。但爲什麼'+ <'與'+ >>'不同。都附加到文件的末尾。 – 2012-04-26 20:14:41

回答

6

文件句柄將在文件的追加模式結尾。

+0

夠公平的。爲什麼文件句柄不在'+ <'模式的文件末尾,這也是附加的? – 2012-04-26 20:17:50

+6

由於您正在以讀寫方式打開,因此它假定您也想從文件讀取。你不應該倒帶一個指針來做到這一點。 – gcochard 2012-04-26 20:19:51

+0

打印告訴FILEHANDLE會告訴你在哪裏文件句柄的位置是 6的RFile,rwfile,分別爲å文件你的情況。 – dpp 2012-04-26 21:05:40