How to get a list of only simple files in a directory using Perl?

I am looking for a way in Perl to list simple directory files. Files only, no directories.

+4
source share
6 answers

You need to use the opendir , readdir and closedir in conjunction with the -f file check statement:

 opendir(my $dh, $some_dir) || die $!; while(my $f = readdir $dh) { next unless (-f "$some_dir/$f"); print "$some_dir/$f\n"; } closedir $dh; 
+11
source

Another way to list all the files in a directory is to use the read_dir function from the CPAN File :: Slurp module:

 use strict; use warnings; use File::Slurp qw(read_dir); my $dir = './'; my @files = grep { -f } read_dir($dir); 

It performs opendir checks for you. Keep in mind that it includes any β€œhidden” files (those starting with a period). This does not recursively list files in subdirectories of the specified directory.

+5
source

You can use the "test" test operator (really a function) to check which file you want.

In the simple case, when you want to scan the current directory, use the glob file with grep:

 my @files = grep -f, <*>; 

Otherwise, you can work with the directory descriptor:

 opendir my $dh, $dirpath; my @files = grep -f, readdir( $dh ); closedir $dh; 

See opendir , readdir , closedir , -X , and grep .

+3
source

Use File :: Find . This is the main module.

 use File::Find; find(\&wanted, @directories_to_search); sub wanted { my $file = shift; return unless (-f $file); #process file } 
+2
source

You need a readdir .

For instance:

 #! /usr/bin/perl use warnings; use strict; my $dir = "/tmp/foo"; opendir my $dh, $dir or die "$0: opendir: $!"; while (defined(my $name = readdir $dh)) { next unless -f "$dir/$name"; print "$name\n"; } 

Launch:

  $ ls -F / tmp / foo
 abcd /

 $ ./prog.pl 
 b
 c
 a 

As you can see, the names come out in the order in which they are physically stored in the file system, which is not necessarily sorted.

To go on a quick and dirty route, you can also use the glob operator, as in

 print map { s!^.*/!!; "$_\n" } grep !-d $_ => </tmp/foo/*>; 

Note that you will have to remove directories from the result, and the glob operator does not return files whose names begin with periods.

+1
source

File :: Find :: Rule from CPAN makes this completely trivial:

 use File::Find::Rule; my @files = File::Find::Rule->file->in( $directory ); 

This finds all files in a given directory or in any of its subdirectories. I recommend this because of the combination of extreme flexibility and simplicity.

+1
source

Source: https://habr.com/ru/post/1309583/


All Articles