http://qs321.pair.com?node_id=805459

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

Dear Monks,

I'm doing a directory listing for files with pattern YYYYMMDD.HHMMSS.host2.pid and want to exclude other files.
I'm using read_dir method from File::Slurp . The below script gives me '0' files after execution. What's wrong with the grep.
use strict; use warnings; use File::Slurp; my $path="/tmp/test"; my @files = grep { -f and /^\d{8}\.\d{6}\.host\d\.\d{1,6}$/ } read_dir + $path; print "Got ". scalar(@files) . "\n";
please point me to the right direction.

Replies are listed 'Best First'.
Re: What's wrong with this grep?
by JavaFan (Canon) on Nov 06, 2009 at 12:27 UTC
    Use -f "$path/$_" instead of -f. read_dir returns file names, not fully qualified paths.
Re: What's wrong with this grep?
by ikegami (Patriarch) on Nov 07, 2009 at 09:35 UTC
    And then there's File::Find::Rule
    use File::Find::Rule qw( ); my @files = File::Find::Rule ->name( qr/^\d{8}\.\d{6}\.host\d\.\d{1,6}$/ ) ->file() ->maxdepth(1) ->in( $path );

    The advantage is that you get qualified file names.

    It's cheaper to execute a regex match than to check if a file is a plain file, so I reversed the order of the tests.

Re: What's wrong with this grep?
by graff (Chancellor) on Nov 07, 2009 at 07:39 UTC
    Alternately to what JavaFan said, you could also do this:
    use File::Slurp; chdir "/tmp/test"; my @files = grep { -f and /^\d{8}\.\d{6}\.host\d\.\d{1,6}$/ } read_dir + "."; print "Got ". scalar(@files) . "\n";
    Of course, if the script is going to do anything else, and needs to keep track of the original working directory, use Cwd to find out where you are before you do chdir.