Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I can't get file find to work.. this is my code:
use File::Find; find(\&wanted, @files); sub wanted { $found ||= $File::Find::name if $_ eq "$item.dat"; }

@files includes . .. dir1 dir2 dir3...

i want to search all directories in @files for $item.dat, and nothing I do seems to work. I want to store the folder that contains $item.dat to $found... $item = 123456, all of my variables are set.. except i can't get the find function to work

Replies are listed 'Best First'.
Re: File::Find
by bikeNomad (Priest) on May 30, 2001 at 01:22 UTC
    You don't show your entire code, so it's hard to tell what's wrong. Presumably, you've looked at the contents of @files and $item somehow. What do you mean that you can't get it to work? Does $found never get set?

    Note that $File::Find::name is not the folder; it's the full file name.

    Note also that you may have to set options to follow symbolic links, etc.

    This entire program works for me:

    #!/usr/bin/perl -w use strict; use File::Find; my @files=qw(. src); my $found; sub wanted { $found ||= $File::Find::name if $_ eq "xx.pl"; } find(\&wanted, @files); print "$found\n";
Re: File::Find
by runrig (Abbot) on May 30, 2001 at 04:22 UTC
    You'd probably like to stop searching when you find your file:
    use File::Find; my $found; find(\&wanted, @files); sub wanted { $File::Find::prune = 1, return if defined $found; $found = $File::Find::name if $_ eq "$item.dat"; }
Re: File::Find
by rchiav (Deacon) on May 30, 2001 at 16:55 UTC
    The other answers should have fixed your problem, but for future debugging refrence, print is your friend.

    When things don't work, start throwing print statements into your code. I woiuld have just printed "found it\n" when the conditional tested true. But you could have gone as far as to do something like..

    sub wanted { print '.'; if ($_ eq "$item.dat")( print "\nfound it!\n"; found = $File::Find::name; } }
    Which wold have shown you each iteration though \&wanted. I always find it easier to validate that the code is doing what I think it's doing when I'm getting unexpected results.

    Hope this helps..
    Rich