Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

What's wrong with this grep?

by chanakya (Friar)
on Nov 06, 2009 at 12:21 UTC ( #805459=perlquestion: print w/replies, xml ) Need Help??

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 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.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://805459]
Approved by moritz
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2023-02-06 23:28 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (37 votes). Check out past polls.