in reply to File::Find: Return array of "wanted" files

Several issues:

Use push to add a member to an array. Here is my attempt to implement what you wanted:

#!/usr/bin/perl use strict; use warnings; use File::Find; sub fgrep { my ($regex, $file) = @_; open my $FH, '<', $file or die $!; while (<$FH>) { return 1 if /$regex/; } return 0; } my @found; sub findstuff { my $file = $_; return unless -f $file; my $fullpath = $File::Find::name; if (fgrep(qr/regex/, $file)) { push @found, $fullpath; } } my @dirs = @ARGV; # Populate @dirs. find(\&findstuff, @dirs); print "@found\n";

Update: push added.

لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: File::Find: Return array of "wanted" files
by alpha-lemming (Novice) on Oct 04, 2013 at 09:52 UTC
    Thanks.

    FWIW, I was using fgrep from File::Grep. I should have included the "use" lines for clarity.

    I actually didn't realize that I can push to @found from within the sub. Guess I better read up some more on scope..

      The scope of a lexical is going from where the lexical is declared to the end of the enclosing block. In the case of @found above, to the end of the file.

        Ah... so if I wanted to push from the sub to the array inside the loop, I would have to declare the array outside of the loop and reinitialise it with every iteration? Or declare the sub inside of the loop?