Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: search for a pattern in file without opening the file

by davorg (Chancellor)
on Jan 29, 2007 at 10:00 UTC ( #597055=note: print w/ replies, xml ) Need Help??


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;


Comment on Re: search for a pattern in file without opening the file
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://597055]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2014-08-30 21:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls