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

i have some problem with searching files. it always return 'File Not Found' althought there's such files. Can you pls help me out? Thanks
find(\&getpm, "$fpath"); sub getpm { if ($File::Find::name =~/readme.txt/) { print "$File::Find::name\n"; else { print "File not Found"; exit(0); } }

Replies are listed 'Best First'.
Re: Searching for files
by slayven (Pilgrim) on Mar 19, 2001 at 08:43 UTC
    first of all find() executes getpm() for every file in $fpath. exit() terminates the perlscript! so you're terminating your perlscript after the first file in $fpath (which isn't readme.txt)

    after eliminating exit(0) you'll see a lot of 'File not Found's after executing. i don't think that you'll like it this way :) you should only print something out, if the file matches.

    finally, the subrouting which find() needs to examine the searchpath, gets the filename assigned to $_ which makes $File::Find::name obsolete.

    so try something like this:
    find(\&getpm, "$fpath"); sub getpm { return unless /readme\.txt/; print $_ . "\n"; }
(dkubb) Re: (2) Searching for files
by dkubb (Deacon) on Mar 19, 2001 at 08:57 UTC

    You might want to examine your regex, you're using a dot inside the filename, which will match one of anything. You may want to escape it using a backslash (\), to make it a literal match. Or better yet, don't use a regex at all, try using eq.

    Also, File::find() will execute getpm() for each file it finds underneath $fpath. More than likely, the first file it's finding is not readme.txt, so it's printing "File not Found", and exiting.

    If you'd like the behaviour of printing "File Not Found" if there is no match, a better idea would be to push any file matches onto an array, then test the array after you're done directory traversing:

    #!/usr/bin/perl -w use strict; use File::Find; use vars qw(@FILES); find(\&getpm, '.'); unless(@FILES) { print "File not Found\n"; exit; } print "$_\n" for @FILES; sub getpm { push @FILES, $File::Find::name if -f && $_ eq 'readme.txt'; };
Re: Searching for files
by ColonelPanic (Friar) on Mar 19, 2001 at 08:43 UTC
    You seem to have left out a closing brace after the first print statement. ;)

    When's the last time you used duct tape on a duct? --Larry Wall