in reply to Re: Problem with regex
in thread Problem with regex

I would actually suggest forgoing the loop altogether and using grep:
my @FILES = grep { -f } readdir (TEMP); foreach my $file (@FILES){ open (F, $file) or warn "Couldn't open $file: $!" and next; my @matches = grep { /$str/ } <F>; close (F); next unless scalar @matches > 0; print join("\n", @matches); }
Of course, that prints every matching line in the file, if you only want the first (evidenced by "last"), you could just use:
print $matches[0], "\n";
And do you really want to use "die" in a loop? What if you can't open one file, but you can open the rest? Isn't "warn and next" more appropriate?

Replies are listed 'Best First'.
Re^3: Problem with regex
by johngg (Canon) on Sep 16, 2008 at 14:49 UTC
    I would actually suggest forgoing the loop altogether and using grep

    Nothing wrong with using grep to fill the @FILES array, although I might do grep { -f and not -l } depending on how symlinks should be treated. However, unless my eyes are failing me, you still have the loop in your code.

    And do you really want to use "die" in a loop?

    The OP seems to and, since I don't know what the requirements are, I followed his/her lead.

    Cheers,

    JohnGG

      Your eyes are not failing you! I clearly should have said I would use fewer loops... my bad!

      We could wrap the loop in a "map" but I don't think it would add to the clarity of the code, so it's probably not worth doing. But I generally find list operators easier to read than nested loops.