1Path::Class::Dir(3) User Contributed Perl Documentation Path::Class::Dir(3)
2
3
4
6 Path::Class::Dir - Objects representing directories
7
9 version 0.37
10
12 use Path::Class; # Exports dir() by default
13
14 my $dir = dir('foo', 'bar'); # Path::Class::Dir object
15 my $dir = Path::Class::Dir->new('foo', 'bar'); # Same thing
16
17 # Stringifies to 'foo/bar' on Unix, 'foo\bar' on Windows, etc.
18 print "dir: $dir\n";
19
20 if ($dir->is_absolute) { ... }
21 if ($dir->is_relative) { ... }
22
23 my $v = $dir->volume; # Could be 'C:' on Windows, empty string
24 # on Unix, 'Macintosh HD:' on Mac OS
25
26 $dir->cleanup; # Perform logical cleanup of pathname
27 $dir->resolve; # Perform physical cleanup of pathname
28
29 my $file = $dir->file('file.txt'); # A file in this directory
30 my $subdir = $dir->subdir('george'); # A subdirectory
31 my $parent = $dir->parent; # The parent directory, 'foo'
32
33 my $abs = $dir->absolute; # Transform to absolute path
34 my $rel = $abs->relative; # Transform to relative path
35 my $rel = $abs->relative('/foo'); # Relative to /foo
36
37 print $dir->as_foreign('Mac'); # :foo:bar:
38 print $dir->as_foreign('Win32'); # foo\bar
39
40 # Iterate with IO::Dir methods:
41 my $handle = $dir->open;
42 while (my $file = $handle->read) {
43 $file = $dir->file($file); # Turn into Path::Class::File object
44 ...
45 }
46
47 # Iterate with Path::Class methods:
48 while (my $file = $dir->next) {
49 # $file is a Path::Class::File or Path::Class::Dir object
50 ...
51 }
52
54 The "Path::Class::Dir" class contains functionality for manipulating
55 directory names in a cross-platform way.
56
58 $dir = Path::Class::Dir->new( <dir1>, <dir2>, ... )
59 $dir = dir( <dir1>, <dir2>, ... )
60 Creates a new "Path::Class::Dir" object and returns it. The
61 arguments specify names of directories which will be joined to
62 create a single directory object. A volume may also be specified
63 as the first argument, or as part of the first argument. You can
64 use platform-neutral syntax:
65
66 my $dir = dir( 'foo', 'bar', 'baz' );
67
68 or platform-native syntax:
69
70 my $dir = dir( 'foo/bar/baz' );
71
72 or a mixture of the two:
73
74 my $dir = dir( 'foo/bar', 'baz' );
75
76 All three of the above examples create relative paths. To create
77 an absolute path, either use the platform native syntax for doing
78 so:
79
80 my $dir = dir( '/var/tmp' );
81
82 or use an empty string as the first argument:
83
84 my $dir = dir( '', 'var', 'tmp' );
85
86 If the second form seems awkward, that's somewhat intentional -
87 paths like "/var/tmp" or "\Windows" aren't cross-platform concepts
88 in the first place (many non-Unix platforms don't have a notion of
89 a "root directory"), so they probably shouldn't appear in your code
90 if you're trying to be cross-platform. The first form is perfectly
91 natural, because paths like this may come from config files, user
92 input, or whatever.
93
94 As a special case, since it doesn't otherwise mean anything useful
95 and it's convenient to define this way, "Path::Class::Dir->new()"
96 (or "dir()") refers to the current directory
97 ("File::Spec->curdir"). To get the current directory as an
98 absolute path, do "dir()->absolute".
99
100 Finally, as another special case "dir(undef)" will return undef,
101 since that's usually an accident on the part of the caller, and
102 returning the root directory would be a nasty surprise just asking
103 for trouble a few lines later.
104
105 $dir->stringify
106 This method is called internally when a "Path::Class::Dir" object
107 is used in a string context, so the following are equivalent:
108
109 $string = $dir->stringify;
110 $string = "$dir";
111
112 $dir->volume
113 Returns the volume (e.g. "C:" on Windows, "Macintosh HD:" on Mac
114 OS, etc.) of the directory object, if any. Otherwise, returns the
115 empty string.
116
117 $dir->basename
118 Returns the last directory name of the path as a string.
119
120 $dir->is_dir
121 Returns a boolean value indicating whether this object represents a
122 directory. Not surprisingly, Path::Class::File objects always
123 return false, and "Path::Class::Dir" objects always return true.
124
125 $dir->is_absolute
126 Returns true or false depending on whether the directory refers to
127 an absolute path specifier (like "/usr/local" or "\Windows").
128
129 $dir->is_relative
130 Returns true or false depending on whether the directory refers to
131 a relative path specifier (like "lib/foo" or "./dir").
132
133 $dir->cleanup
134 Performs a logical cleanup of the file path. For instance:
135
136 my $dir = dir('/foo//baz/./foo')->cleanup;
137 # $dir now represents '/foo/baz/foo';
138
139 $dir->resolve
140 Performs a physical cleanup of the file path. For instance:
141
142 my $dir = dir('/foo//baz/../foo')->resolve;
143 # $dir now represents '/foo/foo', assuming no symlinks
144
145 This actually consults the filesystem to verify the validity of the
146 path.
147
148 $file = $dir->file( <dir1>, <dir2>, ..., <file> )
149 Returns a Path::Class::File object representing an entry in $dir or
150 one of its subdirectories. Internally, this just calls
151 "Path::Class::File->new( @_ )".
152
153 $subdir = $dir->subdir( <dir1>, <dir2>, ... )
154 Returns a new "Path::Class::Dir" object representing a subdirectory
155 of $dir.
156
157 $parent = $dir->parent
158 Returns the parent directory of $dir. Note that this is the
159 logical parent, not necessarily the physical parent. It really
160 means we just chop off entries from the end of the directory list
161 until we cain't chop no more. If the directory is relative, we
162 start using the relative forms of parent directories.
163
164 The following code demonstrates the behavior on absolute and
165 relative directories:
166
167 $dir = dir('/foo/bar');
168 for (1..6) {
169 print "Absolute: $dir\n";
170 $dir = $dir->parent;
171 }
172
173 $dir = dir('foo/bar');
174 for (1..6) {
175 print "Relative: $dir\n";
176 $dir = $dir->parent;
177 }
178
179 ########### Output on Unix ################
180 Absolute: /foo/bar
181 Absolute: /foo
182 Absolute: /
183 Absolute: /
184 Absolute: /
185 Absolute: /
186 Relative: foo/bar
187 Relative: foo
188 Relative: .
189 Relative: ..
190 Relative: ../..
191 Relative: ../../..
192
193 @list = $dir->children
194 Returns a list of Path::Class::File and/or "Path::Class::Dir"
195 objects listed in this directory, or in scalar context the number
196 of such objects. Obviously, it is necessary for $dir to exist and
197 be readable in order to find its children.
198
199 Note that the children are returned as subdirectories of $dir, i.e.
200 the children of foo will be foo/bar and foo/baz, not bar and baz.
201
202 Ordinarily "children()" will not include the self and parent
203 entries "." and ".." (or their equivalents on non-Unix systems),
204 because that's like I'm-my-own-grandpa business. If you do want
205 all directory entries including these special ones, pass a true
206 value for the "all" parameter:
207
208 @c = $dir->children(); # Just the children
209 @c = $dir->children(all => 1); # All entries
210
211 In addition, there's a "no_hidden" parameter that will exclude all
212 normally "hidden" entries - on Unix this means excluding all
213 entries that begin with a dot ("."):
214
215 @c = $dir->children(no_hidden => 1); # Just normally-visible entries
216
217 $abs = $dir->absolute
218 Returns a "Path::Class::Dir" object representing $dir as an
219 absolute path. An optional argument, given as either a string or a
220 "Path::Class::Dir" object, specifies the directory to use as the
221 base of relativity - otherwise the current working directory will
222 be used.
223
224 $rel = $dir->relative
225 Returns a "Path::Class::Dir" object representing $dir as a relative
226 path. An optional argument, given as either a string or a
227 "Path::Class::Dir" object, specifies the directory to use as the
228 base of relativity - otherwise the current working directory will
229 be used.
230
231 $boolean = $dir->subsumes($other)
232 Returns true if this directory spec subsumes the other spec, and
233 false otherwise. Think of "subsumes" as "contains", but we only
234 look at the specs, not whether $dir actually contains $other on the
235 filesystem.
236
237 The $other argument may be a "Path::Class::Dir" object, a
238 Path::Class::File object, or a string. In the latter case, we
239 assume it's a directory.
240
241 # Examples:
242 dir('foo/bar' )->subsumes(dir('foo/bar/baz')) # True
243 dir('/foo/bar')->subsumes(dir('/foo/bar/baz')) # True
244 dir('foo/..')->subsumes(dir('foo/../bar)) # True
245 dir('foo/bar' )->subsumes(dir('bar/baz')) # False
246 dir('/foo/bar')->subsumes(dir('foo/bar')) # False
247 dir('foo/..')->subsumes(dir('bar')) # False! Use C<contains> to resolve ".."
248
249 $boolean = $dir->contains($other)
250 Returns true if this directory actually contains $other on the
251 filesystem. $other doesn't have to be a direct child of $dir, it
252 just has to be subsumed after both paths have been resolved.
253
254 $foreign = $dir->as_foreign($type)
255 Returns a "Path::Class::Dir" object representing $dir as it would
256 be specified on a system of type $type. Known types include
257 "Unix", "Win32", "Mac", "VMS", and "OS2", i.e. anything for which
258 there is a subclass of "File::Spec".
259
260 Any generated objects (subdirectories, files, parents, etc.) will
261 also retain this type.
262
263 $foreign = Path::Class::Dir->new_foreign($type, @args)
264 Returns a "Path::Class::Dir" object representing $dir as it would
265 be specified on a system of type $type. Known types include
266 "Unix", "Win32", "Mac", "VMS", and "OS2", i.e. anything for which
267 there is a subclass of "File::Spec".
268
269 The arguments in @args are the same as they would be specified in
270 "new()".
271
272 @list = $dir->dir_list([OFFSET, [LENGTH]])
273 Returns the list of strings internally representing this directory
274 structure. Each successive member of the list is understood to be
275 an entry in its predecessor's directory list. By contract,
276 "Path::Class->new( $dir->dir_list )" should be equivalent to $dir.
277
278 The semantics of this method are similar to Perl's "splice" or
279 "substr" functions; they return "LENGTH" elements starting at
280 "OFFSET". If "LENGTH" is omitted, returns all the elements
281 starting at "OFFSET" up to the end of the list. If "LENGTH" is
282 negative, returns the elements from "OFFSET" onward except for
283 "-LENGTH" elements at the end. If "OFFSET" is negative, it counts
284 backward "OFFSET" elements from the end of the list. If "OFFSET"
285 and "LENGTH" are both omitted, the entire list is returned.
286
287 In a scalar context, "dir_list()" with no arguments returns the
288 number of entries in the directory list; "dir_list(OFFSET)" returns
289 the single element at that offset; "dir_list(OFFSET, LENGTH)"
290 returns the final element that would have been returned in a list
291 context.
292
293 $dir->components
294 Identical to "dir_list()". It exists because there's an analogous
295 method "dir_list()" in the "Path::Class::File" class that also
296 returns the basename string, so this method lets someone call
297 "components()" without caring whether the object is a file or a
298 directory.
299
300 $fh = $dir->open()
301 Passes $dir to "IO::Dir->open" and returns the result as an IO::Dir
302 object. If the opening fails, "undef" is returned and $! is set.
303
304 $dir->mkpath($verbose, $mode)
305 Passes all arguments, including $dir, to "File::Path::mkpath()" and
306 returns the result (a list of all directories created).
307
308 $dir->rmtree($verbose, $cautious)
309 Passes all arguments, including $dir, to "File::Path::rmtree()" and
310 returns the result (the number of files successfully deleted).
311
312 $dir->remove()
313 Removes the directory, which must be empty. Returns a boolean
314 value indicating whether or not the directory was successfully
315 removed. This method is mainly provided for consistency with
316 "Path::Class::File"'s "remove()" method.
317
318 $dir->tempfile(...)
319 An interface to File::Temp's "tempfile()" function. Just like that
320 function, if you call this in a scalar context, the return value is
321 the filehandle and the file is "unlink"ed as soon as possible
322 (which is immediately on Unix-like platforms). If called in a list
323 context, the return values are the filehandle and the filename.
324
325 The given directory is passed as the "DIR" parameter.
326
327 Here's an example of pretty good usage which doesn't allow race
328 conditions, won't leave yucky tempfiles around on your filesystem,
329 etc.:
330
331 my $fh = $dir->tempfile;
332 print $fh "Here's some data...\n";
333 seek($fh, 0, 0);
334 while (<$fh>) { do something... }
335
336 Or in combination with a "fork":
337
338 my $fh = $dir->tempfile;
339 print $fh "Here's some more data...\n";
340 seek($fh, 0, 0);
341 if ($pid=fork()) {
342 wait;
343 } else {
344 something($_) while <$fh>;
345 }
346
347 $dir_or_file = $dir->next()
348 A convenient way to iterate through directory contents. The first
349 time "next()" is called, it will "open()" the directory and read
350 the first item from it, returning the result as a
351 "Path::Class::Dir" or Path::Class::File object (depending, of
352 course, on its actual type). Each subsequent call to "next()" will
353 simply iterate over the directory's contents, until there are no
354 more items in the directory, and then the undefined value is
355 returned. For example, to iterate over all the regular files in a
356 directory:
357
358 while (my $file = $dir->next) {
359 next unless -f $file;
360 my $fh = $file->open('r') or die "Can't read $file: $!";
361 ...
362 }
363
364 If an error occurs when opening the directory (for instance, it
365 doesn't exist or isn't readable), "next()" will throw an exception
366 with the value of $!.
367
368 $dir->traverse( sub { ... }, @args )
369 Calls the given callback for the root, passing it a continuation
370 function which, when called, will call this recursively on each of
371 its children. The callback function should be of the form:
372
373 sub {
374 my ($child, $cont, @args) = @_;
375 # ...
376 }
377
378 For instance, to calculate the number of files in a directory, you
379 can do this:
380
381 my $nfiles = $dir->traverse(sub {
382 my ($child, $cont) = @_;
383 return sum($cont->(), ($child->is_dir ? 0 : 1));
384 });
385
386 or to calculate the maximum depth of a directory:
387
388 my $depth = $dir->traverse(sub {
389 my ($child, $cont, $depth) = @_;
390 return max($cont->($depth + 1), $depth);
391 }, 0);
392
393 You can also choose not to call the callback in certain situations:
394
395 $dir->traverse(sub {
396 my ($child, $cont) = @_;
397 return if -l $child; # don't follow symlinks
398 # do something with $child
399 return $cont->();
400 });
401
402 $dir->traverse_if( sub { ... }, sub { ... }, @args )
403 traverse with additional "should I visit this child" callback.
404 Particularly useful in case examined tree contains inaccessible
405 directories.
406
407 Canonical example:
408
409 $dir->traverse_if(
410 sub {
411 my ($child, $cont) = @_;
412 # do something with $child
413 return $cont->();
414 },
415 sub {
416 my ($child) = @_;
417 # Process only readable items
418 return -r $child;
419 });
420
421 Second callback gets single parameter: child. Only children for
422 which it returns true will be processed by the first callback.
423
424 Remaining parameters are interpreted as in traverse, in particular
425 "traverse_if(callback, sub { 1 }, @args" is equivalent to
426 "traverse(callback, @args)".
427
428 $dir->recurse( callback => sub {...} )
429 Iterates through this directory and all of its children, and all of
430 its children's children, etc., calling the "callback" subroutine
431 for each entry. This is a lot like what the File::Find module
432 does, and of course "File::Find" will work fine on Path::Class
433 objects, but the advantage of the "recurse()" method is that it
434 will also feed your callback routine "Path::Class" objects rather
435 than just pathname strings.
436
437 The "recurse()" method requires a "callback" parameter specifying
438 the subroutine to invoke for each entry. It will be passed the
439 "Path::Class" object as its first argument.
440
441 "recurse()" also accepts two boolean parameters, "depthfirst" and
442 "preorder" that control the order of recursion. The default is a
443 preorder, breadth-first search, i.e. "depthfirst => 0, preorder =>
444 1". At the time of this writing, all combinations of these two
445 parameters are supported except "depthfirst => 0, preorder => 0".
446
447 "callback" is normally not required to return any value. If it
448 returns special constant "Path::Class::Entity::PRUNE()" (more
449 easily available as "$item->PRUNE"), no children of analyzed item
450 will be analyzed (mostly as if you set "$File::Find::prune=1"). Of
451 course pruning is available only in "preorder", in postorder return
452 value has no effect.
453
454 $st = $file->stat()
455 Invokes "File::stat::stat()" on this directory and returns a
456 "File::stat" object representing the result.
457
458 $st = $file->lstat()
459 Same as "stat()", but if $file is a symbolic link, "lstat()" stats
460 the link instead of the directory the link points to.
461
462 $class = $file->file_class()
463 Returns the class which should be used to create file objects.
464
465 Generally overridden whenever this class is subclassed.
466
468 Ken Williams, kwilliams@cpan.org
469
471 Path::Class, Path::Class::File, File::Spec
472
473
474
475perl v5.34.0 2022-01-21 Path::Class::Dir(3)