in reply to Re^3: File::Find: Return array of "wanted" files
in thread File::Find: Return array of "wanted" files

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?

  • Comment on Re^4: File::Find: Return array of "wanted" files

Replies are listed 'Best First'.
Re^5: File::Find: Return array of "wanted" files
by Laurent_R (Canon) on Oct 04, 2013 at 21:50 UTC

    Yes, in such a case, you want to declare the array before entering the loop. That's what choroba is doing in the suggested code, declaring @found right before entering the loop:

    my @found; sub findstuff { my $file = $_; return unless -f $file; my $fullpath = $File::Find::name; if (fgrep(qr/regex/, $file)) { push @found, $fullpath; } }

      So, to push to the array with the array inside the foreach block, I would do this:

      my @array1; my @array2; foreach (@array1) { undef @array2; find(\&mysub, cwd); ..do stuff with @array2 } sub mysub { my $file = $File::Find::name; ..filter stuff here... push(@array2, $file); }

      Or is there a nore elegant way of doing this?

        Why do you undef @array2 within your foreach loop? Do you need a fresh xopoty of @array2 each time? Probably not.