Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

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

by Corion (Patriarch)
on Jan 29, 2007 at 10:01 UTC ( [id://597057]=note: print w/replies, xml ) Need Help??


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

Well, you need to search through the files' contents instead of searching through the files' names. For example by using the external grep utility or by actually opening the file, reading its contents and looking for the stuff you want. There is no way to find out about the contents of a file without opening it and reading it.

use strict; sub contains_pattern { my ($file,$pattern) = @_; open my $fh, "<", $file or die "Couldn't read '$file': $!"; grep { /$pattern/ } <$fh>; }; my @files = grep { contains_pattern $_, qr/^source*/ } @arr1;

I also notice that you use /^source*/ as your search pattern. This most likely doesn't do what you want unless you want to match all strings starting with sourc (no e).

Update: Added the part about opening the file

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-25 05:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found