http://www.perlmonks.org?node_id=597055


in reply to search for a pattern in file without opening the file

It's impossible to access the contents of a file without opening it. Sometimes you don't need to _explicitly_ open the files as a library or the operating system will do that for you, but if you're accessing the contents of a file in any way, then that file _is_ being opened by someone.

Looking at your code, it seems you've been confused by the fact that Perl's grep function doesn't work the same way as the Unix grep command. The Unix command works on a list of filenames (Unix opens the files and searches them for you) but the Perl function works on a list of strings. The Perl function is actually far more powerful and flexible than the Unix command. In fact, using it to emulate the Unix command is probably the one thing that it's a bit clunky at :-)

So your best solution is to do it the obvious way. Open each file and read it to see if it contains the test you're looking for. You could probably do something clever with @ARGV and <>, but I don't think you'd gain much.

Update: Actually, I probably wouldn't use grep in this case. The trouble with grep is that it always checks the whole list. And with a large list where your search term appears near the beginning, that can be inefficient. I'd do something like this:

sub contains { my ($file, $search) = @_; open my $fh, '<', $file or die $!; while (<$fh>) { return 1 if /$search/; } return; } my @files = grep { contains($_, $search_str) } @arr1;