Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
"be consistent"

Comment on


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;

In reply to Re: search for a pattern in file without opening the file by davorg

and:  <code> code here </code>

  • Please read these before you post! —
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others wandering the Monastery: (2)
    As of 2014-03-17 00:58 GMT
    Find Nodes?
      Voting Booth?

      Have you used a cryptocurrency?

      Results (337 votes), past polls