1Path::Tiny(3) User Contributed Perl Documentation Path::Tiny(3)
2
3
4
6 Path::Tiny - File path utility
7
9 version 0.124
10
12 use Path::Tiny;
13
14 # creating Path::Tiny objects
15
16 $dir = path("/tmp");
17 $foo = path("foo.txt");
18
19 $subdir = $dir->child("foo");
20 $bar = $subdir->child("bar.txt");
21
22 # stringifies as cleaned up path
23
24 $file = path("./foo.txt");
25 print $file; # "foo.txt"
26
27 # reading files
28
29 $guts = $file->slurp;
30 $guts = $file->slurp_utf8;
31
32 @lines = $file->lines;
33 @lines = $file->lines_utf8;
34
35 ($head) = $file->lines( {count => 1} );
36 ($tail) = $file->lines( {count => -1} );
37
38 # writing files
39
40 $bar->spew( @data );
41 $bar->spew_utf8( @data );
42
43 # reading directories
44
45 for ( $dir->children ) { ... }
46
47 $iter = $dir->iterator;
48 while ( my $next = $iter->() ) { ... }
49
51 This module provides a small, fast utility for working with file paths.
52 It is friendlier to use than File::Spec and provides easy access to
53 functions from several other core file handling modules. It aims to be
54 smaller and faster than many alternatives on CPAN, while helping people
55 do many common things in consistent and less error-prone ways.
56
57 Path::Tiny does not try to work for anything except Unix-like and Win32
58 platforms. Even then, it might break if you try something particularly
59 obscure or tortuous. (Quick! What does this mean:
60 "///../../..//./././a//b/.././c/././"? And how does it differ on
61 Win32?)
62
63 All paths are forced to have Unix-style forward slashes. Stringifying
64 the object gives you back the path (after some clean up).
65
66 File input/output methods "flock" handles before reading or writing, as
67 appropriate (if supported by the platform and/or filesystem).
68
69 The *_utf8 methods ("slurp_utf8", "lines_utf8", etc.) operate in raw
70 mode. On Windows, that means they will not have CRLF translation from
71 the ":crlf" IO layer. Installing Unicode::UTF8 0.58 or later will
72 speed up *_utf8 situations in many cases and is highly recommended.
73 Alternatively, installing PerlIO::utf8_strict 0.003 or later will be
74 used in place of the default ":encoding(UTF-8)".
75
76 This module depends heavily on PerlIO layers for correct operation and
77 thus requires Perl 5.008001 or later.
78
80 path
81 $path = path("foo/bar");
82 $path = path("/tmp", "file.txt"); # list
83 $path = path("."); # cwd
84 $path = path("~user/file.txt"); # tilde processing
85
86 Constructs a "Path::Tiny" object. It doesn't matter if you give a file
87 or directory path. It's still up to you to call directory-like methods
88 only on directories and file-like methods only on files. This function
89 is exported automatically by default.
90
91 The first argument must be defined and have non-zero length or an
92 exception will be thrown. This prevents subtle, dangerous errors with
93 code like "path( maybe_undef() )->remove_tree".
94
95 If the first component of the path is a tilde ('~') then the component
96 will be replaced with the output of "glob('~')". If the first
97 component of the path is a tilde followed by a user name then the
98 component will be replaced with output of "glob('~username')".
99 Behaviour for non-existent users depends on the output of "glob" on the
100 system.
101
102 On Windows, if the path consists of a drive identifier without a path
103 component ("C:" or "D:"), it will be expanded to the absolute path of
104 the current directory on that volume using "Cwd::getdcwd()".
105
106 If called with a single "Path::Tiny" argument, the original is returned
107 unless the original is holding a temporary file or directory reference
108 in which case a stringified copy is made.
109
110 $path = path("foo/bar");
111 $temp = Path::Tiny->tempfile;
112
113 $p2 = path($path); # like $p2 = $path
114 $t2 = path($temp); # like $t2 = path( "$temp" )
115
116 This optimizes copies without proliferating references unexpectedly if
117 a copy is made by code outside your control.
118
119 Current API available since 0.017.
120
121 new
122 $path = Path::Tiny->new("foo/bar");
123
124 This is just like "path", but with method call overhead. (Why would
125 you do that?)
126
127 Current API available since 0.001.
128
129 cwd
130 $path = Path::Tiny->cwd; # path( Cwd::getcwd )
131 $path = cwd; # optional export
132
133 Gives you the absolute path to the current directory as a "Path::Tiny"
134 object. This is slightly faster than "path(".")->absolute".
135
136 "cwd" may be exported on request and used as a function instead of as a
137 method.
138
139 Current API available since 0.018.
140
141 rootdir
142 $path = Path::Tiny->rootdir; # /
143 $path = rootdir; # optional export
144
145 Gives you "File::Spec->rootdir" as a "Path::Tiny" object if you're too
146 picky for "path("/")".
147
148 "rootdir" may be exported on request and used as a function instead of
149 as a method.
150
151 Current API available since 0.018.
152
153 tempfile, tempdir
154 $temp = Path::Tiny->tempfile( @options );
155 $temp = Path::Tiny->tempdir( @options );
156 $temp = $dirpath->tempfile( @options );
157 $temp = $dirpath->tempdir( @options );
158 $temp = tempfile( @options ); # optional export
159 $temp = tempdir( @options ); # optional export
160
161 "tempfile" passes the options to "File::Temp->new" and returns a
162 "Path::Tiny" object with the file name. The "TMPDIR" option is enabled
163 by default.
164
165 The resulting "File::Temp" object is cached. When the "Path::Tiny"
166 object is destroyed, the "File::Temp" object will be as well.
167
168 "File::Temp" annoyingly requires you to specify a custom template in
169 slightly different ways depending on which function or method you call,
170 but "Path::Tiny" lets you ignore that and can take either a leading
171 template or a "TEMPLATE" option and does the right thing.
172
173 $temp = Path::Tiny->tempfile( "customXXXXXXXX" ); # ok
174 $temp = Path::Tiny->tempfile( TEMPLATE => "customXXXXXXXX" ); # ok
175
176 The tempfile path object will be normalized to have an absolute path,
177 even if created in a relative directory using "DIR". If you want it to
178 have the "realpath" instead, pass a leading options hash like this:
179
180 $real_temp = tempfile({realpath => 1}, @options);
181
182 "tempdir" is just like "tempfile", except it calls "File::Temp->newdir"
183 instead.
184
185 Both "tempfile" and "tempdir" may be exported on request and used as
186 functions instead of as methods.
187
188 The methods can be called on an instances representing a directory. In
189 this case, the directory is used as the base to create the temporary
190 file/directory, setting the "DIR" option in File::Temp.
191
192 my $target_dir = path('/to/destination');
193 my $tempfile = $target_dir->tempfile('foobarXXXXXX');
194 $tempfile->spew('A lot of data...'); # not atomic
195 $tempfile->move($target_dir->child('foobar')); # hopefully atomic
196
197 In this case, any value set for option "DIR" is ignored.
198
199 Note: for tempfiles, the filehandles from File::Temp are closed and not
200 reused. This is not as secure as using File::Temp handles directly,
201 but is less prone to deadlocks or access problems on some platforms.
202 Think of what "Path::Tiny" gives you to be just a temporary file name
203 that gets cleaned up.
204
205 Note 2: if you don't want these cleaned up automatically when the
206 object is destroyed, File::Temp requires different options for
207 directories and files. Use "CLEANUP => 0" for directories and "UNLINK
208 => 0" for files.
209
210 Note 3: Don't lose the temporary object by chaining a method call
211 instead of storing it:
212
213 my $lost = tempdir()->child("foo"); # tempdir cleaned up right away
214
215 Note 4: The cached object may be accessed with the "cached_temp"
216 method. Keeping a reference to, or modifying the cached object may
217 break the behavior documented above and is not supported. Use at your
218 own risk.
219
220 Current API available since 0.119.
221
223 absolute
224 $abs = path("foo/bar")->absolute;
225 $abs = path("foo/bar")->absolute("/tmp");
226
227 Returns a new "Path::Tiny" object with an absolute path (or itself if
228 already absolute). If no argument is given, the current directory is
229 used as the absolute base path. If an argument is given, it will be
230 converted to an absolute path (if it is not already) and used as the
231 absolute base path.
232
233 This will not resolve upward directories ("foo/../bar") unless
234 "canonpath" in File::Spec would normally do so on your platform. If
235 you need them resolved, you must call the more expensive "realpath"
236 method instead.
237
238 On Windows, an absolute path without a volume component will have it
239 added based on the current drive.
240
241 Current API available since 0.101.
242
243 append, append_raw, append_utf8
244 path("foo.txt")->append(@data);
245 path("foo.txt")->append(\@data);
246 path("foo.txt")->append({binmode => ":raw"}, @data);
247 path("foo.txt")->append_raw(@data);
248 path("foo.txt")->append_utf8(@data);
249
250 Appends data to a file. The file is locked with "flock" prior to
251 writing and closed afterwards. An optional hash reference may be used
252 to pass options. Valid options are:
253
254 • "binmode": passed to "binmode()" on the handle used for writing.
255
256 • "truncate": truncates the file after locking and before appending
257
258 The "truncate" option is a way to replace the contents of a file in
259 place, unlike "spew" which writes to a temporary file and then replaces
260 the original (if it exists).
261
262 "append_raw" is like "append" with a "binmode" of ":unix" for fast,
263 unbuffered, raw write.
264
265 "append_utf8" is like "append" with a "binmode" of
266 ":unix:encoding(UTF-8)" (or PerlIO::utf8_strict). If Unicode::UTF8
267 0.58+ is installed, a raw append will be done instead on the data
268 encoded with "Unicode::UTF8".
269
270 Current API available since 0.060.
271
272 assert
273 $path = path("foo.txt")->assert( sub { $_->exists } );
274
275 Returns the invocant after asserting that a code reference argument
276 returns true. When the assertion code reference runs, it will have the
277 invocant object in the $_ variable. If it returns false, an exception
278 will be thrown. The assertion code reference may also throw its own
279 exception.
280
281 If no assertion is provided, the invocant is returned without error.
282
283 Current API available since 0.062.
284
285 basename
286 $name = path("foo/bar.txt")->basename; # bar.txt
287 $name = path("foo.txt")->basename('.txt'); # foo
288 $name = path("foo.txt")->basename(qr/.txt/); # foo
289 $name = path("foo.txt")->basename(@suffixes);
290
291 Returns the file portion or last directory portion of a path.
292
293 Given a list of suffixes as strings or regular expressions, any that
294 match at the end of the file portion or last directory portion will be
295 removed before the result is returned.
296
297 Current API available since 0.054.
298
299 canonpath
300 $canonical = path("foo/bar")->canonpath; # foo\bar on Windows
301
302 Returns a string with the canonical format of the path name for the
303 platform. In particular, this means directory separators will be "\"
304 on Windows.
305
306 Current API available since 0.001.
307
308 cached_temp
309 Returns the cached "File::Temp" or "File::Temp::Dir" object if the
310 "Path::Tiny" object was created with "/tempfile" or "/tempdir". If
311 there is no such object, this method throws.
312
313 WARNING: Keeping a reference to, or modifying the cached object may
314 break the behavior documented for temporary files and directories
315 created with "Path::Tiny" and is not supported. Use at your own risk.
316
317 Current API available since 0.101.
318
319 child
320 $file = path("/tmp")->child("foo.txt"); # "/tmp/foo.txt"
321 $file = path("/tmp")->child(@parts);
322
323 Returns a new "Path::Tiny" object relative to the original. Works like
324 "catfile" or "catdir" from File::Spec, but without caring about file or
325 directories.
326
327 WARNING: because the argument could contain ".." or refer to symlinks,
328 there is no guarantee that the new path refers to an actual descendent
329 of the original. If this is important to you, transform parent and
330 child with "realpath" and check them with "subsumes".
331
332 Current API available since 0.001.
333
334 children
335 @paths = path("/tmp")->children;
336 @paths = path("/tmp")->children( qr/\.txt\z/ );
337
338 Returns a list of "Path::Tiny" objects for all files and directories
339 within a directory. Excludes "." and ".." automatically.
340
341 If an optional "qr//" argument is provided, it only returns objects for
342 child names that match the given regular expression. Only the base
343 name is used for matching:
344
345 @paths = path("/tmp")->children( qr/^foo/ );
346 # matches children like the glob foo*
347
348 Current API available since 0.028.
349
350 chmod
351 path("foo.txt")->chmod(0777);
352 path("foo.txt")->chmod("0755");
353 path("foo.txt")->chmod("go-w");
354 path("foo.txt")->chmod("a=r,u+wx");
355
356 Sets file or directory permissions. The argument can be a numeric
357 mode, a octal string beginning with a "0" or a limited subset of the
358 symbolic mode use by /bin/chmod.
359
360 The symbolic mode must be a comma-delimited list of mode clauses.
361 Clauses must match "qr/\A([augo]+)([=+-])([rwx]+)\z/", which defines
362 "who", "op" and "perms" parameters for each clause. Unlike /bin/chmod,
363 all three parameters are required for each clause, multiple ops are not
364 allowed and permissions "stugoX" are not supported. (See File::chmod
365 for more complex needs.)
366
367 Current API available since 0.053.
368
369 copy
370 path("/tmp/foo.txt")->copy("/tmp/bar.txt");
371
372 Copies the current path to the given destination using File::Copy's
373 "copy" function. Upon success, returns the "Path::Tiny" object for the
374 newly copied file.
375
376 Current API available since 0.070.
377
378 digest
379 $obj = path("/tmp/foo.txt")->digest; # SHA-256
380 $obj = path("/tmp/foo.txt")->digest("MD5"); # user-selected
381 $obj = path("/tmp/foo.txt")->digest( { chunk_size => 1e6 }, "MD5" );
382
383 Returns a hexadecimal digest for a file. An optional hash reference of
384 options may be given. The only option is "chunk_size". If
385 "chunk_size" is given, that many bytes will be read at a time. If not
386 provided, the entire file will be slurped into memory to compute the
387 digest.
388
389 Any subsequent arguments are passed to the constructor for Digest to
390 select an algorithm. If no arguments are given, the default is
391 SHA-256.
392
393 Current API available since 0.056.
394
395 dirname (deprecated)
396 $name = path("/tmp/foo.txt")->dirname; # "/tmp/"
397
398 Returns the directory portion you would get from calling
399 "File::Spec->splitpath( $path->stringify )" or "." for a path without a
400 parent directory portion. Because File::Spec is inconsistent, the
401 result might or might not have a trailing slash. Because of this, this
402 method is deprecated.
403
404 A better, more consistently approach is likely
405 "$path->parent->stringify", which will not have a trailing slash except
406 for a root directory.
407
408 Deprecated in 0.056.
409
410 edit, edit_raw, edit_utf8
411 path("foo.txt")->edit( \&callback, $options );
412 path("foo.txt")->edit_utf8( \&callback );
413 path("foo.txt")->edit_raw( \&callback );
414
415 These are convenience methods that allow "editing" a file using a
416 single callback argument. They slurp the file using "slurp", place the
417 contents inside a localized $_ variable, call the callback function
418 (without arguments), and then write $_ (presumably mutated) back to the
419 file with "spew".
420
421 An optional hash reference may be used to pass options. The only
422 option is "binmode", which is passed to "slurp" and "spew".
423
424 "edit_utf8" and "edit_raw" act like their respective "slurp_*" and
425 "spew_*" methods.
426
427 Current API available since 0.077.
428
429 edit_lines, edit_lines_utf8, edit_lines_raw
430 path("foo.txt")->edit_lines( \&callback, $options );
431 path("foo.txt")->edit_lines_utf8( \&callback );
432 path("foo.txt")->edit_lines_raw( \&callback );
433
434 These are convenience methods that allow "editing" a file's lines using
435 a single callback argument. They iterate over the file: for each line,
436 the line is put into a localized $_ variable, the callback function is
437 executed (without arguments) and then $_ is written to a temporary
438 file. When iteration is finished, the temporary file is atomically
439 renamed over the original.
440
441 An optional hash reference may be used to pass options. The only
442 option is "binmode", which is passed to the method that open handles
443 for reading and writing.
444
445 "edit_lines_utf8" and "edit_lines_raw" act like their respective
446 "slurp_*" and "spew_*" methods.
447
448 Current API available since 0.077.
449
450 exists, is_file, is_dir
451 if ( path("/tmp")->exists ) { ... } # -e
452 if ( path("/tmp")->is_dir ) { ... } # -d
453 if ( path("/tmp")->is_file ) { ... } # -e && ! -d
454
455 Implements file test operations, this means the file or directory
456 actually has to exist on the filesystem. Until then, it's just a path.
457
458 Note: "is_file" is not "-f" because "-f" is not the opposite of "-d".
459 "-f" means "plain file", excluding symlinks, devices, etc. that often
460 can be read just like files.
461
462 Use "-f" instead if you really mean to check for a plain file.
463
464 Current API available since 0.053.
465
466 filehandle
467 $fh = path("/tmp/foo.txt")->filehandle($mode, $binmode);
468 $fh = path("/tmp/foo.txt")->filehandle({ locked => 1 }, $mode, $binmode);
469 $fh = path("/tmp/foo.txt")->filehandle({ exclusive => 1 }, $mode, $binmode);
470
471 Returns an open file handle. The $mode argument must be a Perl-style
472 read/write mode string ("<" ,">", ">>", etc.). If a $binmode is given,
473 it is set during the "open" call.
474
475 An optional hash reference may be used to pass options.
476
477 The "locked" option governs file locking; if true, handles opened for
478 writing, appending or read-write are locked with "LOCK_EX"; otherwise,
479 they are locked with "LOCK_SH". When using "locked", ">" or "+>" modes
480 will delay truncation until after the lock is acquired.
481
482 The "exclusive" option causes the open() call to fail if the file
483 already exists. This corresponds to the O_EXCL flag to sysopen /
484 open(2). "exclusive" implies "locked" and will set it for you if you
485 forget it.
486
487 See "openr", "openw", "openrw", and "opena" for sugar.
488
489 Current API available since 0.066.
490
491 is_absolute, is_relative
492 if ( path("/tmp")->is_absolute ) { ... }
493 if ( path("/tmp")->is_relative ) { ... }
494
495 Booleans for whether the path appears absolute or relative.
496
497 Current API available since 0.001.
498
499 is_rootdir
500 while ( ! $path->is_rootdir ) {
501 $path = $path->parent;
502 ...
503 }
504
505 Boolean for whether the path is the root directory of the volume. I.e.
506 the "dirname" is "q[/]" and the "basename" is "q[]".
507
508 This works even on "MSWin32" with drives and UNC volumes:
509
510 path("C:/")->is_rootdir; # true
511 path("//server/share/")->is_rootdir; #true
512
513 Current API available since 0.038.
514
515 iterator
516 $iter = path("/tmp")->iterator( \%options );
517
518 Returns a code reference that walks a directory lazily. Each
519 invocation returns a "Path::Tiny" object or undef when the iterator is
520 exhausted.
521
522 $iter = path("/tmp")->iterator;
523 while ( $path = $iter->() ) {
524 ...
525 }
526
527 The current and parent directory entries ("." and "..") will not be
528 included.
529
530 If the "recurse" option is true, the iterator will walk the directory
531 recursively, breadth-first. If the "follow_symlinks" option is also
532 true, directory links will be followed recursively. There is no
533 protection against loops when following links. If a directory is not
534 readable, it will not be followed.
535
536 The default is the same as:
537
538 $iter = path("/tmp")->iterator( {
539 recurse => 0,
540 follow_symlinks => 0,
541 } );
542
543 For a more powerful, recursive iterator with built-in loop avoidance,
544 see Path::Iterator::Rule.
545
546 See also "visit".
547
548 Current API available since 0.016.
549
550 lines, lines_raw, lines_utf8
551 @contents = path("/tmp/foo.txt")->lines;
552 @contents = path("/tmp/foo.txt")->lines(\%options);
553 @contents = path("/tmp/foo.txt")->lines_raw;
554 @contents = path("/tmp/foo.txt")->lines_utf8;
555
556 @contents = path("/tmp/foo.txt")->lines( { chomp => 1, count => 4 } );
557
558 Returns a list of lines from a file. Optionally takes a hash-reference
559 of options. Valid options are "binmode", "count" and "chomp".
560
561 If "binmode" is provided, it will be set on the handle prior to
562 reading.
563
564 If a positive "count" is provided, that many lines will be returned
565 from the start of the file. If a negative "count" is provided, the
566 entire file will be read, but only "abs(count)" will be kept and
567 returned. If "abs(count)" exceeds the number of lines in the file, all
568 lines will be returned.
569
570 If "chomp" is set, any end-of-line character sequences ("CR", "CRLF",
571 or "LF") will be removed from the lines returned.
572
573 Because the return is a list, "lines" in scalar context will return the
574 number of lines (and throw away the data).
575
576 $number_of_lines = path("/tmp/foo.txt")->lines;
577
578 "lines_raw" is like "lines" with a "binmode" of ":raw". We use ":raw"
579 instead of ":unix" so PerlIO buffering can manage reading by line.
580
581 "lines_utf8" is like "lines" with a "binmode" of ":raw:encoding(UTF-8)"
582 (or PerlIO::utf8_strict). If Unicode::UTF8 0.58+ is installed, a raw
583 UTF-8 slurp will be done and then the lines will be split. This is
584 actually faster than relying on ":encoding(UTF-8)", though a bit memory
585 intensive. If memory use is a concern, consider "openr_utf8" and
586 iterating directly on the handle.
587
588 Current API available since 0.065.
589
590 mkpath
591 path("foo/bar/baz")->mkpath;
592 path("foo/bar/baz")->mkpath( \%options );
593
594 Like calling "make_path" from File::Path. An optional hash reference
595 is passed through to "make_path". Errors will be trapped and an
596 exception thrown. Returns the list of directories created or an empty
597 list if the directories already exist, just like "make_path".
598
599 See also "touchpath" as a chainable alternative to create a writeable
600 file path (though without options).
601
602 Current API available since 0.001.
603
604 move
605 path("foo.txt")->move("bar.txt");
606
607 Move the current path to the given destination path using Perl's built-
608 in rename function. Returns the result of the "rename" function (except
609 it throws an exception if it fails).
610
611 Current API available since 0.001.
612
613 openr, openw, openrw, opena
614 $fh = path("foo.txt")->openr($binmode); # read
615 $fh = path("foo.txt")->openr_raw;
616 $fh = path("foo.txt")->openr_utf8;
617
618 $fh = path("foo.txt")->openw($binmode); # write
619 $fh = path("foo.txt")->openw_raw;
620 $fh = path("foo.txt")->openw_utf8;
621
622 $fh = path("foo.txt")->opena($binmode); # append
623 $fh = path("foo.txt")->opena_raw;
624 $fh = path("foo.txt")->opena_utf8;
625
626 $fh = path("foo.txt")->openrw($binmode); # read/write
627 $fh = path("foo.txt")->openrw_raw;
628 $fh = path("foo.txt")->openrw_utf8;
629
630 Returns a file handle opened in the specified mode. The "openr" style
631 methods take a single "binmode" argument. All of the "open*" methods
632 have "open*_raw" and "open*_utf8" equivalents that use ":raw" and
633 ":raw:encoding(UTF-8)", respectively.
634
635 An optional hash reference may be used to pass options. The only
636 option is "locked". If true, handles opened for writing, appending or
637 read-write are locked with "LOCK_EX"; otherwise, they are locked for
638 "LOCK_SH".
639
640 $fh = path("foo.txt")->openrw_utf8( { locked => 1 } );
641
642 See "filehandle" for more on locking.
643
644 Current API available since 0.011.
645
646 parent
647 $parent = path("foo/bar/baz")->parent; # foo/bar
648 $parent = path("foo/wibble.txt")->parent; # foo
649
650 $parent = path("foo/bar/baz")->parent(2); # foo
651
652 Returns a "Path::Tiny" object corresponding to the parent directory of
653 the original directory or file. An optional positive integer argument
654 is the number of parent directories upwards to return. "parent" by
655 itself is equivalent to parent(1).
656
657 Current API available since 0.014.
658
659 realpath
660 $real = path("/baz/foo/../bar")->realpath;
661 $real = path("foo/../bar")->realpath;
662
663 Returns a new "Path::Tiny" object with all symbolic links and upward
664 directory parts resolved using Cwd's "realpath". Compared to
665 "absolute", this is more expensive as it must actually consult the
666 filesystem.
667
668 If the parent path can't be resolved (e.g. if it includes directories
669 that don't exist), an exception will be thrown:
670
671 $real = path("doesnt_exist/foo")->realpath; # dies
672
673 However, if the parent path exists and only the last component (e.g.
674 filename) doesn't exist, the realpath will be the realpath of the
675 parent plus the non-existent last component:
676
677 $real = path("./aasdlfasdlf")->realpath; # works
678
679 The underlying Cwd module usually worked this way on Unix, but died on
680 Windows (and some Unixes) if the full path didn't exist. As of version
681 0.064, it's safe to use anywhere.
682
683 Current API available since 0.001.
684
685 relative
686 $rel = path("/tmp/foo/bar")->relative("/tmp"); # foo/bar
687
688 Returns a "Path::Tiny" object with a path relative to a new base path
689 given as an argument. If no argument is given, the current directory
690 will be used as the new base path.
691
692 If either path is already relative, it will be made absolute based on
693 the current directly before determining the new relative path.
694
695 The algorithm is roughly as follows:
696
697 • If the original and new base path are on different volumes, an
698 exception will be thrown.
699
700 • If the original and new base are identical, the relative path is
701 ".".
702
703 • If the new base subsumes the original, the relative path is the
704 original path with the new base chopped off the front
705
706 • If the new base does not subsume the original, a common prefix path
707 is determined (possibly the root directory) and the relative path
708 will consist of updirs ("..") to reach the common prefix, followed
709 by the original path less the common prefix.
710
711 Unlike "File::Spec::abs2rel", in the last case above, the calculation
712 based on a common prefix takes into account symlinks that could affect
713 the updir process. Given an original path "/A/B" and a new base
714 "/A/C", (where "A", "B" and "C" could each have multiple path
715 components):
716
717 • Symlinks in "A" don't change the result unless the last component
718 of A is a symlink and the first component of "C" is an updir.
719
720 • Symlinks in "B" don't change the result and will exist in the
721 result as given.
722
723 • Symlinks and updirs in "C" must be resolved to actual paths, taking
724 into account the possibility that not all path components might
725 exist on the filesystem.
726
727 Current API available since 0.001. New algorithm (that accounts for
728 symlinks) available since 0.079.
729
730 remove
731 path("foo.txt")->remove;
732
733 This is just like "unlink", except for its error handling: if the path
734 does not exist, it returns false; if deleting the file fails, it throws
735 an exception.
736
737 Current API available since 0.012.
738
739 remove_tree
740 # directory
741 path("foo/bar/baz")->remove_tree;
742 path("foo/bar/baz")->remove_tree( \%options );
743 path("foo/bar/baz")->remove_tree( { safe => 0 } ); # force remove
744
745 Like calling "remove_tree" from File::Path, but defaults to "safe"
746 mode. An optional hash reference is passed through to "remove_tree".
747 Errors will be trapped and an exception thrown. Returns the number of
748 directories deleted, just like "remove_tree".
749
750 If you want to remove a directory only if it is empty, use the built-in
751 "rmdir" function instead.
752
753 rmdir path("foo/bar/baz/");
754
755 Current API available since 0.013.
756
757 sibling
758 $foo = path("/tmp/foo.txt");
759 $sib = $foo->sibling("bar.txt"); # /tmp/bar.txt
760 $sib = $foo->sibling("baz", "bam.txt"); # /tmp/baz/bam.txt
761
762 Returns a new "Path::Tiny" object relative to the parent of the
763 original. This is slightly more efficient than
764 "$path->parent->child(...)".
765
766 Current API available since 0.058.
767
768 size, size_human
769 my $p = path("foo"); # with size 1025 bytes
770
771 $p->size; # "1025"
772 $p->size_human; # "1.1 K"
773 $p->size_human( {format => "iec"} ); # "1.1 KiB"
774
775 Returns the size of a file. The "size" method is just a wrapper around
776 "-s".
777
778 The "size_human" method provides a human-readable string similar to "ls
779 -lh". Like "ls", it rounds upwards and provides one decimal place for
780 single-digit sizes and no decimal places for larger sizes. The only
781 available option is "format", which has three valid values:
782
783 • 'ls' (the default): base-2 sizes, with "ls" style single-letter
784 suffixes (K, M, etc.)
785
786 • 'iec': base-2 sizes, with IEC binary suffixes (KiB, MiB, etc.)
787
788 • 'si': base-10 sizes, with SI decimal suffixes (kB, MB, etc.)
789
790 If "-s" would return "undef", "size_human" returns the empty string.
791
792 Current API available since 0.122.
793
794 slurp, slurp_raw, slurp_utf8
795 $data = path("foo.txt")->slurp;
796 $data = path("foo.txt")->slurp( {binmode => ":raw"} );
797 $data = path("foo.txt")->slurp_raw;
798 $data = path("foo.txt")->slurp_utf8;
799
800 Reads file contents into a scalar. Takes an optional hash reference
801 which may be used to pass options. The only available option is
802 "binmode", which is passed to "binmode()" on the handle used for
803 reading.
804
805 "slurp_raw" is like "slurp" with a "binmode" of ":unix" for a fast,
806 unbuffered, raw read.
807
808 "slurp_utf8" is like "slurp" with a "binmode" of
809 ":unix:encoding(UTF-8)" (or PerlIO::utf8_strict). If Unicode::UTF8
810 0.58+ is installed, a raw slurp will be done instead and the result
811 decoded with "Unicode::UTF8". This is just as strict and is roughly an
812 order of magnitude faster than using ":encoding(UTF-8)".
813
814 Note: "slurp" and friends lock the filehandle before slurping. If you
815 plan to slurp from a file created with File::Temp, be sure to close
816 other handles or open without locking to avoid a deadlock:
817
818 my $tempfile = File::Temp->new(EXLOCK => 0);
819 my $guts = path($tempfile)->slurp;
820
821 Current API available since 0.004.
822
823 spew, spew_raw, spew_utf8
824 path("foo.txt")->spew(@data);
825 path("foo.txt")->spew(\@data);
826 path("foo.txt")->spew({binmode => ":raw"}, @data);
827 path("foo.txt")->spew_raw(@data);
828 path("foo.txt")->spew_utf8(@data);
829
830 Writes data to a file atomically. The file is written to a temporary
831 file in the same directory, then renamed over the original. An
832 optional hash reference may be used to pass options. The only option
833 is "binmode", which is passed to "binmode()" on the handle used for
834 writing.
835
836 "spew_raw" is like "spew" with a "binmode" of ":unix" for a fast,
837 unbuffered, raw write.
838
839 "spew_utf8" is like "spew" with a "binmode" of ":unix:encoding(UTF-8)"
840 (or PerlIO::utf8_strict). If Unicode::UTF8 0.58+ is installed, a raw
841 spew will be done instead on the data encoded with "Unicode::UTF8".
842
843 NOTE: because the file is written to a temporary file and then renamed,
844 the new file will wind up with permissions based on your current umask.
845 This is a feature to protect you from a race condition that would
846 otherwise give different permissions than you might expect. If you
847 really want to keep the original mode flags, use "append" with the
848 "truncate" option.
849
850 Current API available since 0.011.
851
852 stat, lstat
853 $stat = path("foo.txt")->stat;
854 $stat = path("/some/symlink")->lstat;
855
856 Like calling "stat" or "lstat" from File::stat.
857
858 Current API available since 0.001.
859
860 stringify
861 $path = path("foo.txt");
862 say $path->stringify; # same as "$path"
863
864 Returns a string representation of the path. Unlike "canonpath", this
865 method returns the path standardized with Unix-style "/" directory
866 separators.
867
868 Current API available since 0.001.
869
870 subsumes
871 path("foo/bar")->subsumes("foo/bar/baz"); # true
872 path("/foo/bar")->subsumes("/foo/baz"); # false
873
874 Returns true if the first path is a prefix of the second path at a
875 directory boundary.
876
877 This does not resolve parent directory entries ("..") or symlinks:
878
879 path("foo/bar")->subsumes("foo/bar/../baz"); # true
880
881 If such things are important to you, ensure that both paths are
882 resolved to the filesystem with "realpath":
883
884 my $p1 = path("foo/bar")->realpath;
885 my $p2 = path("foo/bar/../baz")->realpath;
886 if ( $p1->subsumes($p2) ) { ... }
887
888 Current API available since 0.048.
889
890 touch
891 path("foo.txt")->touch;
892 path("foo.txt")->touch($epoch_secs);
893
894 Like the Unix "touch" utility. Creates the file if it doesn't exist,
895 or else changes the modification and access times to the current time.
896 If the first argument is the epoch seconds then it will be used.
897
898 Returns the path object so it can be easily chained with other methods:
899
900 # won't die if foo.txt doesn't exist
901 $content = path("foo.txt")->touch->slurp;
902
903 Current API available since 0.015.
904
905 touchpath
906 path("bar/baz/foo.txt")->touchpath;
907
908 Combines "mkpath" and "touch". Creates the parent directory if it
909 doesn't exist, before touching the file. Returns the path object like
910 "touch" does.
911
912 Current API available since 0.022.
913
914 visit
915 path("/tmp")->visit( \&callback, \%options );
916
917 Executes a callback for each child of a directory. It returns a hash
918 reference with any state accumulated during iteration.
919
920 The options are the same as for "iterator" (which it uses internally):
921 "recurse" and "follow_symlinks". Both default to false.
922
923 The callback function will receive a "Path::Tiny" object as the first
924 argument and a hash reference to accumulate state as the second
925 argument. For example:
926
927 # collect files sizes
928 my $sizes = path("/tmp")->visit(
929 sub {
930 my ($path, $state) = @_;
931 return if $path->is_dir;
932 $state->{$path} = -s $path;
933 },
934 { recurse => 1 }
935 );
936
937 For convenience, the "Path::Tiny" object will also be locally aliased
938 as the $_ global variable:
939
940 # print paths matching /foo/
941 path("/tmp")->visit( sub { say if /foo/ }, { recurse => 1} );
942
943 If the callback returns a reference to a false scalar value, iteration
944 will terminate. This is not the same as "pruning" a directory search;
945 this just stops all iteration and returns the state hash reference.
946
947 # find up to 10 files larger than 100K
948 my $files = path("/tmp")->visit(
949 sub {
950 my ($path, $state) = @_;
951 $state->{$path}++ if -s $path > 102400
952 return \0 if keys %$state == 10;
953 },
954 { recurse => 1 }
955 );
956
957 If you want more flexible iteration, use a module like
958 Path::Iterator::Rule.
959
960 Current API available since 0.062.
961
962 volume
963 $vol = path("/tmp/foo.txt")->volume; # ""
964 $vol = path("C:/tmp/foo.txt")->volume; # "C:"
965
966 Returns the volume portion of the path. This is equivalent to what
967 File::Spec would give from "splitpath" and thus usually is the empty
968 string on Unix-like operating systems or the drive letter for an
969 absolute path on "MSWin32".
970
971 Current API available since 0.001.
972
974 Simple usage errors will generally croak. Failures of underlying Perl
975 functions will be thrown as exceptions in the class
976 "Path::Tiny::Error".
977
978 A "Path::Tiny::Error" object will be a hash reference with the
979 following fields:
980
981 • "op" — a description of the operation, usually function call and
982 any extra info
983
984 • "file" — the file or directory relating to the error
985
986 • "err" — hold $! at the time the error was thrown
987
988 • "msg" — a string combining the above data and a Carp-like short
989 stack trace
990
991 Exception objects will stringify as the "msg" field.
992
994 PERL_PATH_TINY_NO_FLOCK
995 If the environment variable "PERL_PATH_TINY_NO_FLOCK" is set to a true
996 value then flock will NOT be used when accessing files (this is not
997 recommended).
998
1000 Subclassing not supported
1001 For speed, this class is implemented as an array based object and uses
1002 many direct function calls internally. You must not subclass it and
1003 expect things to work properly.
1004
1005 File locking
1006 If flock is not supported on a platform, it will not be used, even if
1007 locking is requested.
1008
1009 In situations where a platform normally would support locking, but the
1010 flock fails due to a filesystem limitation, Path::Tiny has some
1011 heuristics to detect this and will warn once and continue in an unsafe
1012 mode. If you want this failure to be fatal, you can fatalize the
1013 'flock' warnings category:
1014
1015 use warnings FATAL => 'flock';
1016
1017 See additional caveats below.
1018
1019 NFS and BSD
1020
1021 On BSD, Perl's flock implementation may not work to lock files on an
1022 NFS filesystem. If detected, this situation will warn once, as
1023 described above.
1024
1025 Lustre
1026
1027 The Lustre filesystem does not support flock. If detected, this
1028 situation will warn once, as described above.
1029
1030 AIX and locking
1031
1032 AIX requires a write handle for locking. Therefore, calls that
1033 normally open a read handle and take a shared lock instead will open a
1034 read-write handle and take an exclusive lock. If the user does not
1035 have write permission, no lock will be used.
1036
1037 utf8 vs UTF-8
1038 All the *_utf8 methods by default use ":encoding(UTF-8)" -- either as
1039 ":unix:encoding(UTF-8)" (unbuffered) or ":raw:encoding(UTF-8)"
1040 (buffered) -- which is strict against the Unicode spec and disallows
1041 illegal Unicode codepoints or UTF-8 sequences.
1042
1043 Unfortunately, ":encoding(UTF-8)" is very, very slow. If you install
1044 Unicode::UTF8 0.58 or later, that module will be used by some *_utf8
1045 methods to encode or decode data after a raw, binary input/output
1046 operation, which is much faster. Alternatively, if you install
1047 PerlIO::utf8_strict, that will be used instead of ":encoding(UTF-8)"
1048 and is also very fast.
1049
1050 If you need the performance and can accept the security risk,
1051 "slurp({binmode => ":unix:utf8"})" will be faster than
1052 ":unix:encoding(UTF-8)" (but not as fast as "Unicode::UTF8").
1053
1054 Note that the *_utf8 methods read in raw mode. There is no CRLF
1055 translation on Windows. If you must have CRLF translation, use the
1056 regular input/output methods with an appropriate binmode:
1057
1058 $path->spew_utf8($data); # raw
1059 $path->spew({binmode => ":encoding(UTF-8)"}, $data; # LF -> CRLF
1060
1061 Default IO layers and the open pragma
1062 If you have Perl 5.10 or later, file input/output methods ("slurp",
1063 "spew", etc.) and high-level handle opening methods ( "filehandle",
1064 "openr", "openw", etc. ) respect default encodings set by the "-C"
1065 switch or lexical open settings of the caller. For UTF-8, this is
1066 almost certainly slower than using the dedicated "_utf8" methods if you
1067 have Unicode::UTF8.
1068
1070 A standard MooseX::Types library is available at
1071 MooseX::Types::Path::Tiny. A Type::Tiny equivalent is available as
1072 Types::Path::Tiny.
1073
1075 These are other file/path utilities, which may offer a different
1076 feature set than "Path::Tiny".
1077
1078 • File::chmod
1079
1080 • File::Fu
1081
1082 • IO::All
1083
1084 • Path::Class
1085
1086 These iterators may be slightly faster than the recursive iterator in
1087 "Path::Tiny":
1088
1089 • Path::Iterator::Rule
1090
1091 • File::Next
1092
1093 There are probably comparable, non-Tiny tools. Let me know if you want
1094 me to add a module to the list.
1095
1096 This module was featured in the 2013 Perl Advent Calendar
1097 <http://www.perladvent.org/2013/2013-12-18.html>.
1098
1100 Bugs / Feature Requests
1101 Please report any bugs or feature requests through the issue tracker at
1102 <https://github.com/dagolden/Path-Tiny/issues>. You will be notified
1103 automatically of any progress on your issue.
1104
1105 Source Code
1106 This is open source software. The code repository is available for
1107 public review and contribution under the terms of the license.
1108
1109 <https://github.com/dagolden/Path-Tiny>
1110
1111 git clone https://github.com/dagolden/Path-Tiny.git
1112
1114 David Golden <dagolden@cpan.org>
1115
1117 • Alex Efros <powerman@powerman.name>
1118
1119 • Aristotle Pagaltzis <pagaltzis@gmx.de>
1120
1121 • Chris Williams <bingos@cpan.org>
1122
1123 • Dan Book <grinnz@grinnz.com>
1124
1125 • Dave Rolsky <autarch@urth.org>
1126
1127 • David Steinbrunner <dsteinbrunner@pobox.com>
1128
1129 • Doug Bell <madcityzen@gmail.com>
1130
1131 • Flavio Poletti <flavio@polettix.it>
1132
1133 • Gabor Szabo <szabgab@cpan.org>
1134
1135 • Gabriel Andrade <gabiruh@gmail.com>
1136
1137 • George Hartzell <hartzell@cpan.org>
1138
1139 • Geraud Continsouzas <geraud@scsi.nc>
1140
1141 • Goro Fuji <gfuji@cpan.org>
1142
1143 • Graham Knop <haarg@haarg.org>
1144
1145 • Graham Ollis <plicease@cpan.org>
1146
1147 • Ian Sillitoe <ian@sillit.com>
1148
1149 • James Hunt <james@niftylogic.com>
1150
1151 • John Karr <brainbuz@brainbuz.org>
1152
1153 • Karen Etheridge <ether@cpan.org>
1154
1155 • Mark Ellis <mark.ellis@cartridgesave.co.uk>
1156
1157 • Martin H. Sluka <fany@cpan.org>
1158
1159 • Martin Kjeldsen <mk@bluepipe.dk>
1160
1161 • Michael G. Schwern <mschwern@cpan.org>
1162
1163 • Nigel Gregoire <nigelgregoire@gmail.com>
1164
1165 • Philippe Bruhat (BooK) <book@cpan.org>
1166
1167 • regina-verbae <regina-verbae@users.noreply.github.com>
1168
1169 • Roy Ivy III <rivy@cpan.org>
1170
1171 • Shlomi Fish <shlomif@shlomifish.org>
1172
1173 • Smylers <Smylers@stripey.com>
1174
1175 • Tatsuhiko Miyagawa <miyagawa@bulknews.net>
1176
1177 • Toby Inkster <tobyink@cpan.org>
1178
1179 • Yanick Champoux <yanick@babyl.dyndns.org>
1180
1181 • 김도형 - Keedi Kim <keedi@cpan.org>
1182
1184 This software is Copyright (c) 2014 by David Golden.
1185
1186 This is free software, licensed under:
1187
1188 The Apache License, Version 2.0, January 2004
1189
1190
1191
1192perl v5.36.0 2022-09-02 Path::Tiny(3)