Christopher Karel
Christopher Karel

Reputation: 113

Perl open() and grep

OK, so I've noticed some counter intuitive behavior of grep in perl, depending on how I open a file. If I open a file read only, (<) it works. If I open it read-write, (+<), it works, but if I open it append-read, it does not. (+>>)

I'm sure this can be worked around, but I'm curious as to why it works this way. Anyone have a good explanation?

Given a test.txt file of:

a
b
c

and a greptest.pl file of:

#!/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;

Running it returns following:

$ ./greptest.pl 
Found when opened read
Found when opened write-read
Not found when opened append-read

Whereas I would have expected it to find on all three tests.

Upvotes: 1

Views: 1881

Answers (1)

dpp
dpp

Reputation: 1758

File handle would be at the end of the file for append mode.

Upvotes: 6

Related Questions