in reply to how to assign output of Find() into a variable $

There are many many ways to do that trick. One way is to wrap a call to the callback sub and pass a "return" parameter into it:

#!/usr/bin/perl use warnings; use strict; use File::Find; my @filtered = 'aaa/'; my @results; find(sub {callback(\@results)}, @filtered); print "$_\n" for @results; sub callback { my ($results) = @_; push @$results, $File::Find::name if /\.pl$/; }

There are variations on the theme that involve using global variables in various ways or variations that work well with object oriented techniques. Avoiding globals is good for maintainable code and the object oriented variations tend to be trivial changes to the code shown.

Premature optimization is the root of all job security

Replies are listed 'Best First'.
Re^2: how to assign output of Find() into a variable $
by Tux (Canon) on May 18, 2016 at 09:30 UTC

    Why so complicated? (a sub in a sub)

    use strict; use warnings; use File::Find; my @result; find (sub { m/\.pl$/ and push @result, $File::Find::name; }, "aaa");

    Enjoy, Have FUN! H.Merijn

      Because I hate javaScript nested functions!

      Actually, for a trivial sub the inline sub is fine. For something that does a little more work the inline call to the callback sub allows parameters to be passed and much more maintainable code.

      Premature optimization is the root of all job security
Re^2: how to assign output of Find() into a variable $
by BillKSmith (Monsignor) on May 18, 2016 at 13:21 UTC
    I agree that global variables are almost always undesirable. I do not think that accessing the same variable by reference rather than by name justifies the added complexity. Perhaps it would be better to restrict the scope of the 'global' variable by placing it in a subroutine along with the call to find.
    Bill

      Those sort of decision depend a great deal on context. The OP is almost context free so showing the "complex" version provides a robust scale-able pattern and a good starting point for further discussion.

      It's not clear to me how localizing the global (to the callback) variable avoids the need to pass the variable to the callback if the callback is out of line. Obviously if the callback is inline there is no need to pass in the variable and then it really doesn't matter what the scope of the variable is.

      Premature optimization is the root of all job security