Path::Class::Dir(3) | User Contributed Perl Documentation | Path::Class::Dir(3) |
Path::Class::Dir - Objects representing directories
version 0.37
use Path::Class; # Exports dir() by default my $dir = dir('foo', 'bar'); # Path::Class::Dir object my $dir = Path::Class::Dir->new('foo', 'bar'); # Same thing # Stringifies to 'foo/bar' on Unix, 'foo\bar' on Windows, etc. print "dir: $dir\n"; if ($dir->is_absolute) { ... } if ($dir->is_relative) { ... } my $v = $dir->volume; # Could be 'C:' on Windows, empty string # on Unix, 'Macintosh HD:' on Mac OS $dir->cleanup; # Perform logical cleanup of pathname $dir->resolve; # Perform physical cleanup of pathname my $file = $dir->file('file.txt'); # A file in this directory my $subdir = $dir->subdir('george'); # A subdirectory my $parent = $dir->parent; # The parent directory, 'foo' my $abs = $dir->absolute; # Transform to absolute path my $rel = $abs->relative; # Transform to relative path my $rel = $abs->relative('/foo'); # Relative to /foo print $dir->as_foreign('Mac'); # :foo:bar: print $dir->as_foreign('Win32'); # foo\bar # Iterate with IO::Dir methods: my $handle = $dir->open; while (my $file = $handle->read) { $file = $dir->file($file); # Turn into Path::Class::File object ... } # Iterate with Path::Class methods: while (my $file = $dir->next) { # $file is a Path::Class::File or Path::Class::Dir object ... }
The "Path::Class::Dir" class contains functionality for manipulating directory names in a cross-platform way.
my $dir = dir( 'foo', 'bar', 'baz' );
or platform-native syntax:
my $dir = dir( 'foo/bar/baz' );
or a mixture of the two:
my $dir = dir( 'foo/bar', 'baz' );
All three of the above examples create relative paths. To create an absolute path, either use the platform native syntax for doing so:
my $dir = dir( '/var/tmp' );
or use an empty string as the first argument:
my $dir = dir( '', 'var', 'tmp' );
If the second form seems awkward, that's somewhat intentional - paths like "/var/tmp" or "\Windows" aren't cross-platform concepts in the first place (many non-Unix platforms don't have a notion of a "root directory"), so they probably shouldn't appear in your code if you're trying to be cross-platform. The first form is perfectly natural, because paths like this may come from config files, user input, or whatever.
As a special case, since it doesn't otherwise mean anything useful and it's convenient to define this way, "Path::Class::Dir->new()" (or "dir()") refers to the current directory ("File::Spec->curdir"). To get the current directory as an absolute path, do "dir()->absolute".
Finally, as another special case "dir(undef)" will return undef, since that's usually an accident on the part of the caller, and returning the root directory would be a nasty surprise just asking for trouble a few lines later.
$string = $dir->stringify; $string = "$dir";
my $dir = dir('/foo//baz/./foo')->cleanup; # $dir now represents '/foo/baz/foo';
my $dir = dir('/foo//baz/../foo')->resolve; # $dir now represents '/foo/foo', assuming no symlinks
This actually consults the filesystem to verify the validity of the path.
The following code demonstrates the behavior on absolute and relative directories:
$dir = dir('/foo/bar'); for (1..6) { print "Absolute: $dir\n"; $dir = $dir->parent; } $dir = dir('foo/bar'); for (1..6) { print "Relative: $dir\n"; $dir = $dir->parent; } ########### Output on Unix ################ Absolute: /foo/bar Absolute: /foo Absolute: / Absolute: / Absolute: / Absolute: / Relative: foo/bar Relative: foo Relative: . Relative: .. Relative: ../.. Relative: ../../..
Note that the children are returned as subdirectories of $dir, i.e. the children of foo will be foo/bar and foo/baz, not bar and baz.
Ordinarily "children()" will not include the self and parent entries "." and ".." (or their equivalents on non-Unix systems), because that's like I'm-my-own-grandpa business. If you do want all directory entries including these special ones, pass a true value for the "all" parameter:
@c = $dir->children(); # Just the children @c = $dir->children(all => 1); # All entries
In addition, there's a "no_hidden" parameter that will exclude all normally "hidden" entries - on Unix this means excluding all entries that begin with a dot ("."):
@c = $dir->children(no_hidden => 1); # Just normally-visible entries
The $other argument may be a "Path::Class::Dir" object, a Path::Class::File object, or a string. In the latter case, we assume it's a directory.
# Examples: dir('foo/bar' )->subsumes(dir('foo/bar/baz')) # True dir('/foo/bar')->subsumes(dir('/foo/bar/baz')) # True dir('foo/..')->subsumes(dir('foo/../bar)) # True dir('foo/bar' )->subsumes(dir('bar/baz')) # False dir('/foo/bar')->subsumes(dir('foo/bar')) # False dir('foo/..')->subsumes(dir('bar')) # False! Use C<contains> to resolve ".."
Any generated objects (subdirectories, files, parents, etc.) will also retain this type.
The arguments in @args are the same as they would be specified in "new()".
The semantics of this method are similar to Perl's "splice" or "substr" functions; they return "LENGTH" elements starting at "OFFSET". If "LENGTH" is omitted, returns all the elements starting at "OFFSET" up to the end of the list. If "LENGTH" is negative, returns the elements from "OFFSET" onward except for "-LENGTH" elements at the end. If "OFFSET" is negative, it counts backward "OFFSET" elements from the end of the list. If "OFFSET" and "LENGTH" are both omitted, the entire list is returned.
In a scalar context, "dir_list()" with no arguments returns the number of entries in the directory list; "dir_list(OFFSET)" returns the single element at that offset; "dir_list(OFFSET, LENGTH)" returns the final element that would have been returned in a list context.
The given directory is passed as the "DIR" parameter.
Here's an example of pretty good usage which doesn't allow race conditions, won't leave yucky tempfiles around on your filesystem, etc.:
my $fh = $dir->tempfile; print $fh "Here's some data...\n"; seek($fh, 0, 0); while (<$fh>) { do something... }
Or in combination with a "fork":
my $fh = $dir->tempfile; print $fh "Here's some more data...\n"; seek($fh, 0, 0); if ($pid=fork()) { wait; } else { something($_) while <$fh>; }
while (my $file = $dir->next) { next unless -f $file; my $fh = $file->open('r') or die "Can't read $file: $!"; ... }
If an error occurs when opening the directory (for instance, it doesn't exist or isn't readable), "next()" will throw an exception with the value of $!.
sub { my ($child, $cont, @args) = @_; # ... }
For instance, to calculate the number of files in a directory, you can do this:
my $nfiles = $dir->traverse(sub { my ($child, $cont) = @_; return sum($cont->(), ($child->is_dir ? 0 : 1)); });
or to calculate the maximum depth of a directory:
my $depth = $dir->traverse(sub { my ($child, $cont, $depth) = @_; return max($cont->($depth + 1), $depth); }, 0);
You can also choose not to call the callback in certain situations:
$dir->traverse(sub { my ($child, $cont) = @_; return if -l $child; # don't follow symlinks # do something with $child return $cont->(); });
Canonical example:
$dir->traverse_if( sub { my ($child, $cont) = @_; # do something with $child return $cont->(); }, sub { my ($child) = @_; # Process only readable items return -r $child; });
Second callback gets single parameter: child. Only children for which it returns true will be processed by the first callback.
Remaining parameters are interpreted as in traverse, in particular "traverse_if(callback, sub { 1 }, @args" is equivalent to "traverse(callback, @args)".
The "recurse()" method requires a "callback" parameter specifying the subroutine to invoke for each entry. It will be passed the "Path::Class" object as its first argument.
"recurse()" also accepts two boolean parameters, "depthfirst" and "preorder" that control the order of recursion. The default is a preorder, breadth-first search, i.e. "depthfirst => 0, preorder => 1". At the time of this writing, all combinations of these two parameters are supported except "depthfirst => 0, preorder => 0".
"callback" is normally not required to return any value. If it returns special constant "Path::Class::Entity::PRUNE()" (more easily available as "$item->PRUNE"), no children of analyzed item will be analyzed (mostly as if you set "$File::Find::prune=1"). Of course pruning is available only in "preorder", in postorder return value has no effect.
Generally overridden whenever this class is subclassed.
Ken Williams, kwilliams@cpan.org
Path::Class, Path::Class::File, File::Spec
2024-04-13 | perl v5.34.0 |