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

Hi Monks!
How do a search for a specific file in a directory? Like:
opendir(DIR, $dir) or die "can't opendir $dir: $!"; @files = readdir( DIR ) or die "Couldn't read from $dir : $!\n"; @files = grep @files, { /\errors.txt$/ && -f $_ }; print "*****A found your file here!******<br>";

Something like that would work, but it's not working, any help!

Replies are listed 'Best First'.
Re: A file in a directory
by davidrw (Prior) on Apr 24, 2006 at 18:15 UTC
    In general, please always define "it's not working" with the error message..

    Your grep arguments are backwards:
    @files = grep { /\errors.txt$/ && -f $_ }, @files;
    Related topics: glob, File::Find, File::Find::Rule (example below)
    my @files = File::Find::Rule->file()->name('errors.txt')->maxdepth(1)- +>in($dir);
    Also, if you're going for just one specific file, no need to read the directory -- just check directly if the file exists:
    my $file = $dir . '/errors.txt'; push @files, $file if -f $file;
      Sure, I just needed to go specifically to the file, thanks!
Re: A file in a directory
by bart (Canon) on Apr 24, 2006 at 18:57 UTC
    I don't see why you don't simply try to access the file "$dir/errors.txt".

    With the file test operators you can see if it exists, and access various properties; stat can be used to do the same. Note that the -X operators don't produce an error in case the file doesn't exist. Instead, they tend to return undef. stat returns an empty list.