I'm trying to get the name of all directories in the specified path
I tried the following but that gives me every level down not just at the path i specified
find(\&dir_names, "C:\\mydata\\");
sub dir_names {
print "$File::Find::dir\n" if(-f $File::Find::dir,'/');
}
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 .
You can use readdir or glob. Or, Path::Tiny: @paths = path("/tmp")->children; @paths = path("/tmp")->children( qr/\. txt$/ );
glob() function in Perl is used to print the files present in a directory passed to it as an argument. This function can print all or the specific files whose extension has been passed to it. Syntax: glob(Directory_name/File_type); Parameter: path of the directory of which files are to be printed.
Traversing files and directories in Perl can also be done through File::Find module which comes with the Perl language. Find: find () function performs a depth-first search on the mentioned/defined @directories. It calls and invokes the "&wanted" function for each file or sub-directory found in that directory. find () works from top to down.
You can use rmdir function to remove a directory. You will need to have the required permission to remove a directory. Additionally this directory should be empty before you try to remove it. #!/usr/bin/perl $dir = "/tmp/perl"; # This removes perl directory from /tmp directory.
Change a Directory. You can use chdir function to change a directory and go to a new location. You will need to have the required permission to change a directory and go inside the new directory. #!/usr/bin/perl $dir = "/home"; # This changes perl directory and moves you inside /home directory.
Find modules in Perl has all the functions similar to the Unix Find command. 1st argument is a subroutine called for each file which we found through find function. 2nd argument is the list of the directories where find function is going to search the files. Example 1: To print all the available directories in the searched folder.
Use opendir
instead
opendir DIR, $dirname or die "Couldn't open dir '$dirname': $!";
my @files = readdir(DIR);
closedir DIR;
#next processing...
EDIT:
"This will give all the files, not just the directories. You'd still have to grep."
Yes, and in that case you can just use file test operator to see whether it's a directory or not.
In Windows:
$dirname="C:\\";
opendir(DIR, $dirname);
@files = readdir(DIR);
closedir DIR;
foreach $key (@files)
{
if(-d "$dirname\\$key")
{
print "$key\n";
}
}
my @dirs = grep { -d } glob 'C:\mydata\*';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With