Reputation: 1
There may be syntax errors as I'm doing this from memory, but:
use strict;
use warnings;
open(FILE, "+>file") or die "can't open";
print FILE "foo";
if (grep {/^foo$/m}, <FILE>) {
print "bar";
}
close(FILE) or die "can't close";
Why doesn't this print bar and how should I do this? I'm writing to a file and I need to check in the future if I've written certain things to the file before continuing, ie. if foo already exists then don't write foo.
Upvotes: 0
Views: 94
Reputation: 845
There are a few problems with the code that could be causing this.
The output to the file may be buffered so reading from the file will not see the output until after the buffer has been flushed to the file.
In addition when you write to the file the file handle's location is moved to the end of where you have written so the read will not see it. This isn't tested but you should be looking along the lines of something like this.
use Modern::Perl;
use Fcntl qw(SEEK_SET);
open(my $file_handle, "+>", "file") or die "can't open";
print $file_handle "foo";
$file_handle->flush;
seek $file_handle, 0, SEEK_SET);
if (grep {/^foo$/m}, <$file_handle>) {
print "bar\n";
}
close($file_handle) or die "can't close";
Upvotes: 0
Reputation:
Reading data from a file (e.g, <FILE>
) starts reading from the current file pointer, not from the start of the file. In this case, that ends up being the end of the file — nothing gets read.
If you wanted to restart reading from the beginning, you could seek to the beginning first:
seek FILE, 0, 0;
However, keep in mind that this will be very inefficient. If you expect this to be a common operation, you'll be much better off storing the things you've written to an array and searching through that.
Upvotes: 3