好的,所以我注意到perl中grep的一些反直觉行为,具体取决于我打开文件的方式。如果我打开一个只读文件,(<)它可以工作。如果我打开它读写,(+<),它可以工作,但如果我打开它追加读取,它不会。 (+ GT;&GT)
我确信这可以解决,但我很好奇它为什么这样工作。任何人都有一个很好的解释?
给出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 :(得分:6)
文件句柄位于附加模式文件的末尾。