1

好的,所以我注意到 perl 中 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

而我原以为它会在所有三个测试中找到。

4

1 回答 1

6

文件句柄将位于附加模式的文件末尾。

于 2012-04-26T20:17:04.433 回答