Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I list all of the files in a directory with Perl? [duplicate]

Tags:

directory

perl

People also ask

How do I list all files in a directory in Perl?

If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir: opendir my $dir, "/some/path" or die "Cannot open directory: $!"; my @files = readdir $dir; closedir $dir; You can also use: my @files = glob( $dir .

How do I loop through all files in Perl?

You can use readdir or glob. Or, Path::Tiny: @paths = path("/tmp")->children; @paths = path("/tmp")->children( qr/\. txt$/ );

What is chdir in Perl?

chdir EXPR chdir FILEHANDLE chdir DIRHANDLE chdir. Changes the working directory to EXPR, if possible. If EXPR is omitted, changes to the directory specified by $ENV{HOME} , if set; if not, changes to the directory specified by $ENV{LOGDIR} .


If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir:

opendir my $dir, "/some/path" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;

You can also use:

my @files = glob( $dir . '/*' );

But in my opinion it is not as good - mostly because glob is quite complex thing (can filter results automatically) and using it to get all elements of directory seems as a too simple task.

On the other hand, if you need to get content from all of the directories and subdirectories, there is basically one standard solution:

use File::Find;

my @content;
find( \&wanted, '/some/path');
do_something_with( @content );

exit;

sub wanted {
  push @content, $File::Find::name;
  return;
}

readdir() does that.

Check http://perldoc.perl.org/functions/readdir.html

opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;

this should do it.

my $dir = "bla/bla/upload";
opendir DIR,$dir;
my @dir = readdir(DIR);
close DIR;
foreach(@dir){
    if (-f $dir . "/" . $_ ){
        print $_,"   : file\n";
    }elsif(-d $dir . "/" . $_){
        print $_,"   : folder\n";
    }else{
        print $_,"   : other\n";
    }
}

Or File::Find

use File::Find;
finddepth(\&wanted, '/some/path/to/dir');
sub wanted { print };

It'll go through subdirectories if they exist.