OK、ファイルを開く方法によっては、perlでのgrepの直感に反する動作に気づきました。読み取り専用のファイルを開くと、(<)は機能します。読み取り/書き込み(+ <)を開くと機能しますが、append-readを開くと機能しません。(+ >>)
これは回避できると確信していますが、なぜこのように機能するのか興味があります。誰か良い説明がありますか?
与えられた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
私はそれが3つのテストすべてで見つかると思っていたのに対して。