'Perl subroutine to return all files recursively in a directory [closed]
I am a newcomer to perl, while I can write code to print all file names in a directory in perl, I am not sure how to write a subroutine which will return the same to its caller function
Solution 1:[1]
Use the File::Find module:
#! /usr/bin/perl
use warnings;
use strict;
use File::Find;
sub get_all_files {
my ($dir) = @_;
my @files;
# Use $File::Find::name instead of $_ to get the paths.
find(sub { push @files, $_ }, $dir);
return @files
}
my $dir = shift;
my @files = get_all_files($dir);
print "$_\n" for @files;
Solution 2:[2]
Try this
You want to search the file into directory simply use File::Find module. Or else you should create recursive subroutine to do it.
my $path = "/home";
find($path);
sub find{
my ($s) = @_;
foreach my $files (glob "$s/*")
{
if(-f $files)
{
print "$files \n";
}
elsif(-d $files)
{
find("$files")
}
}
}
Here -d used to check if the content is a directory. -f used to check content is a file.
First pass the name of the directory into the find subroutine. Then get the value by using $s variable, glob/* list the all files in the path. Then iterate the loop for the particulary directory files. If files exists it comes in the if block if folders exist it comes in to the elsif. Then the folder name goto the subroutine again and so on.
Solution 3:[3]
Learn to find stuff in the documentation.
Start with "perldoc perlfaq" and you will find:
perlfaq5 - Files and Formats
Then look at "perldoc perlfaq5" and search for "directory". You will find:
How do I traverse a directory tree? (contributed by brian d foy)
The File::Find module, which comes with Perl, does all of the hard work to traverse a
directory structure. It comes with Perl. You simply call the "find" subroutine with a
callback subroutine and the directories you want to traverse:
use File::Find;
find( \&wanted, @directories );
sub wanted {
# full path in $File::Find::name
# just filename in $_
... do whatever you want to do ...
}
The File::Find::Closures, which you can download from CPAN, provides many ready-to-use
subroutines that you can use with File::Find.
The File::Finder, which you can download from CPAN, can help you create the callback
subroutine using something closer to the syntax of the "find" command-line utility:
use File::Find;
use File::Finder;
my $deep_dirs = File::Finder->depth->type('d')->ls->exec('rmdir','{}');
find( $deep_dirs->as_options, @places );
The File::Find::Rule module, which you can download from CPAN, has a similar interface,
but does the traversal for you too:
use File::Find::Rule;
my @files = File::Find::Rule->file()
->name( '*.pm' )
->in( @INC );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | choroba |
| Solution 2 | |
| Solution 3 | neuhaus |
