Weeeelllll...
First I add strict & warnings since I'm paranoid.
I also notice that I'm not checking the return values of the open, flock and close, which could cause problems, so we sprinkle a few die statements in appropriate places.
I'm using a fixed constant in the "flock", which is naughty, so we'll load up Fcntl to get the proper constants in - I assume that I want a shared lock since that's what "1" normally is.
(I am, of course, also assuming that whatever is potentially fiddling with these files is also being nice and using flock properly - the wonders of co-operative locking :-)
Since regexes are pretty darn fast, it almost certainly doesn't make sense to read in the whole file into memory for the sake of shortening the time of the lock. So we change the loop so we examine each line as we read it in.
Hmmm... "$lines" should probably be called "$line" since it's only a single line.
In this:
push(@search, $line) if grep { /$query/ } $line;
As grep says, you're misunderstanding what grep does. Since we're just looking at a single line we can just use a simple match like this
push @search, $line if $line =~ m/$query/;
Note: this assumes that $query might be a regex. If you want it to be interpreted literally you would need to do:
push @search, $line if $line =~ m/\Q$query/;
(ammendum... actually you should really use index since the regex match would be overkill)
Put all of this together and we get
use strict;
use warnings;
use Fcntl ':flock';
my @search;
my $query = "perl";
open(FILE, "/Users/adrianh/Desktop/myfile.txt") or die;
flock(FILE, LOCK_SH) or die;
foreach my $line (<FILE>) {
chomp($line);
push @search, $line if $line =~ m/\Q$query/;
}
close(FILE) or die;
Your test of "@search" should work as you expect... for example:
print "We found...\n", @search ? join("\n", @search) : "nowt\n";
so I suspect some other problem with the script run caused it not to fire.
Maybe you should consider some tests :-) :-)
Hope this helps. |