首页 文章

Perl open()和grep

提问于
浏览
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

虽然我希望它能在所有三个测试中找到它 .

1 回答

  • 6

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

相关问题