It depends on what you want. If you want a full listing of what files you have, optionally with some extra data, modification date, size etc, File::Find is your best option, IMO. That is a standard module, BTW.
$dir = shift || '.';
use File::Find;
use File::Spec::Functions 'rel2abs';
find sub {
(my $full = $File::Find::name) =~ tr[/][\\];
printf "%s %6d %s\n", (-d $_ ? 'd' : 'f'), -s _, $full;
}, rel2abs($dir);
| [reply] [d/l] |
For a simple look at directories, look at opendir, readdir, closedir and perldoc -f -X to test if a file is a normal file, a directory, or something else.
You probably want File::Find and a bit of thought.
If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
That way everyone learns.
| [reply] |
To see this implemented without any modules, you can look at the following code (look at my note at the end, though):
#!perl
use strict;
use warnings;
sub printDir {
my $headDir = shift; # get starting directory
our $indent = 3; # indentation
our $increase = 3; # indentation steps
sub recurseDir {
my ($home, $dir) = @_; # get home directory and current di
+rectory
unless (-d "$home\\$dir") { # if it is a file
print " " x $indent . "$dir\n"; # just print its name
return;
}
print " " x $indent . "[$dir]\n"; # it's a dir, so print its nam
+e fancily
opendir(DIR, "$home\\$dir") # let's have a look at the dir
+'s contents
or die "Failed to open '$home\\$dir': $!\n";
my @filelist = readdir DIR; # get them
closedir DIR; # close the handle
$indent += $increase; # increase indentation for nex
+t recursion level
for (@filelist) { # iterate through dir contents
next if ($_ eq '.' or $_ eq '..'); # ignore if . or ..
recurseDir("$home\\$dir", $_); # and recurse otherwise
}
$indent -= $increase; # restore indentation
}
unless (-d "$headDir") {
print " " x $indent . "$headDir\n";
return;
}
print " " x $indent . "[$headDir]\n";
opendir(DIR, $headDir) or die "Failed to open '$headDir': $!\n";
my @filelist = readdir DIR;
closedir DIR;
$indent += $increase;
for (@filelist) {
next if ($_ eq '.' or $_ eq '..');
recurseDir($headDir, $_);
}
}
printDir 'C:\Dokumente';
In real life, however, (if it exists ;-) you should always use File::Find or a similar module to make your code more portable and easy to read. Furthermore ther are some traps, like links and such, which might render this simple solution useless. Conclusion: Always use File::Find or a similar module.
Hope this helped.
CombatSquirrel.
Entropy is the tendency of everything going to hell. | [reply] [d/l] |