in reply to Re^2: while following perl hack book
in thread while following perl hack book

sub { some code } generates an anonymous subroutine and returns a reference to it. So:
find( { wanted => sub { blah blah } }, @dirs );
is the same as
sub foo { blah blah } find( { wanted => \&foo }, @dirs );
but without declaring a separate, named subroutine.

Update: fixed to pass hashref and array

Replies are listed 'Best First'.
Re^4: while following perl hack book
by convenientstore (Pilgrim) on Feb 04, 2008 at 20:04 UTC
    I understand now about the anonymous subroutine. I went over both anonymous sub and also the cpan's doc on this at http://search.cpan.org/~rgarcia/perl-5.10.0/lib/File/Find.pm
    However, I still do not understand ..

    Doc says that find(\&wanted, @directories);, find function will do a depth search in @directories and for each file/dir found, it will call a anonymous sub wanted
    couple questions
    1)why is there a curly brace for find at below? find{}, instead of bracket??
    All the example I been looking at has find()
    2)why are they omitting the second parameter ? list of directories?
    Or shouldn't the whole thing be written as
    find( sub { ##code here; }, @INC, );
    instead of how it's written in the book?

    find{ wanted => sub { ##### code ;}, no_chdir => 1,}, $incl_dir;
      Look at the synopsis in File::Find again. Passing a hashref instead of a coderef (i.e. { wanted => ..., }) allows (but doesn't require) you to specify other options, like no_chdir or follow.

      1. The hack author just omitted the parens. When find is predeclared (or imported in this case), these two lines are identical:
        find sub { ... }, $dir_name ; find( sub { ... }, $dir_name );
      2. I thought that as well, but when I tried to refactor to the more efficient form (passing all directories at once), I noticed that the code in the &wanted sub needs to know the "root" directory name: $file =~ s{^\Q$incl_dir/\E}{ };. Passing all the dirs at once removes the ability to see $incl_dir.

        thank you guys as always
        These closure, anonymous sub and callback are little bit over my head, so I must do more reading and coding on the subject
        I will comment more on this as I learn more