1Path::Tiny(3)         User Contributed Perl Documentation        Path::Tiny(3)
2
3
4

NAME

6       Path::Tiny - File path utility
7

VERSION

9       version 0.122
10

SYNOPSIS

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

DESCRIPTION

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

CONSTRUCTORS

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->rename($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

METHODS

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       Current API available since 0.001.
600
601   move
602           path("foo.txt")->move("bar.txt");
603
604       Move the current path to the given destination path using Perl's built-
605       in rename function. Returns the result of the "rename" function (except
606       it throws an exception if it fails).
607
608       Current API available since 0.001.
609
610   openr, openw, openrw, opena
611           $fh = path("foo.txt")->openr($binmode);  # read
612           $fh = path("foo.txt")->openr_raw;
613           $fh = path("foo.txt")->openr_utf8;
614
615           $fh = path("foo.txt")->openw($binmode);  # write
616           $fh = path("foo.txt")->openw_raw;
617           $fh = path("foo.txt")->openw_utf8;
618
619           $fh = path("foo.txt")->opena($binmode);  # append
620           $fh = path("foo.txt")->opena_raw;
621           $fh = path("foo.txt")->opena_utf8;
622
623           $fh = path("foo.txt")->openrw($binmode); # read/write
624           $fh = path("foo.txt")->openrw_raw;
625           $fh = path("foo.txt")->openrw_utf8;
626
627       Returns a file handle opened in the specified mode.  The "openr" style
628       methods take a single "binmode" argument.  All of the "open*" methods
629       have "open*_raw" and "open*_utf8" equivalents that use ":raw" and
630       ":raw:encoding(UTF-8)", respectively.
631
632       An optional hash reference may be used to pass options.  The only
633       option is "locked".  If true, handles opened for writing, appending or
634       read-write are locked with "LOCK_EX"; otherwise, they are locked for
635       "LOCK_SH".
636
637           $fh = path("foo.txt")->openrw_utf8( { locked => 1 } );
638
639       See "filehandle" for more on locking.
640
641       Current API available since 0.011.
642
643   parent
644           $parent = path("foo/bar/baz")->parent; # foo/bar
645           $parent = path("foo/wibble.txt")->parent; # foo
646
647           $parent = path("foo/bar/baz")->parent(2); # foo
648
649       Returns a "Path::Tiny" object corresponding to the parent directory of
650       the original directory or file. An optional positive integer argument
651       is the number of parent directories upwards to return.  "parent" by
652       itself is equivalent to parent(1).
653
654       Current API available since 0.014.
655
656   realpath
657           $real = path("/baz/foo/../bar")->realpath;
658           $real = path("foo/../bar")->realpath;
659
660       Returns a new "Path::Tiny" object with all symbolic links and upward
661       directory parts resolved using Cwd's "realpath".  Compared to
662       "absolute", this is more expensive as it must actually consult the
663       filesystem.
664
665       If the parent path can't be resolved (e.g. if it includes directories
666       that don't exist), an exception will be thrown:
667
668           $real = path("doesnt_exist/foo")->realpath; # dies
669
670       However, if the parent path exists and only the last component (e.g.
671       filename) doesn't exist, the realpath will be the realpath of the
672       parent plus the non-existent last component:
673
674           $real = path("./aasdlfasdlf")->realpath; # works
675
676       The underlying Cwd module usually worked this way on Unix, but died on
677       Windows (and some Unixes) if the full path didn't exist.  As of version
678       0.064, it's safe to use anywhere.
679
680       Current API available since 0.001.
681
682   relative
683           $rel = path("/tmp/foo/bar")->relative("/tmp"); # foo/bar
684
685       Returns a "Path::Tiny" object with a path relative to a new base path
686       given as an argument.  If no argument is given, the current directory
687       will be used as the new base path.
688
689       If either path is already relative, it will be made absolute based on
690       the current directly before determining the new relative path.
691
692       The algorithm is roughly as follows:
693
694       •   If the original and new base path are on different volumes, an
695           exception will be thrown.
696
697       •   If the original and new base are identical, the relative path is
698           ".".
699
700       •   If the new base subsumes the original, the relative path is the
701           original path with the new base chopped off the front
702
703       •   If the new base does not subsume the original, a common prefix path
704           is determined (possibly the root directory) and the relative path
705           will consist of updirs ("..") to reach the common prefix, followed
706           by the original path less the common prefix.
707
708       Unlike "File::Spec::abs2rel", in the last case above, the calculation
709       based on a common prefix takes into account symlinks that could affect
710       the updir process.  Given an original path "/A/B" and a new base
711       "/A/C", (where "A", "B" and "C" could each have multiple path
712       components):
713
714       •   Symlinks in "A" don't change the result unless the last component
715           of A is a symlink and the first component of "C" is an updir.
716
717       •   Symlinks in "B" don't change the result and will exist in the
718           result as given.
719
720       •   Symlinks and updirs in "C" must be resolved to actual paths, taking
721           into account the possibility that not all path components might
722           exist on the filesystem.
723
724       Current API available since 0.001.  New algorithm (that accounts for
725       symlinks) available since 0.079.
726
727   remove
728           path("foo.txt")->remove;
729
730       This is just like "unlink", except for its error handling: if the path
731       does not exist, it returns false; if deleting the file fails, it throws
732       an exception.
733
734       Current API available since 0.012.
735
736   remove_tree
737           # directory
738           path("foo/bar/baz")->remove_tree;
739           path("foo/bar/baz")->remove_tree( \%options );
740           path("foo/bar/baz")->remove_tree( { safe => 0 } ); # force remove
741
742       Like calling "remove_tree" from File::Path, but defaults to "safe"
743       mode.  An optional hash reference is passed through to "remove_tree".
744       Errors will be trapped and an exception thrown.  Returns the number of
745       directories deleted, just like "remove_tree".
746
747       If you want to remove a directory only if it is empty, use the built-in
748       "rmdir" function instead.
749
750           rmdir path("foo/bar/baz/");
751
752       Current API available since 0.013.
753
754   sibling
755           $foo = path("/tmp/foo.txt");
756           $sib = $foo->sibling("bar.txt");        # /tmp/bar.txt
757           $sib = $foo->sibling("baz", "bam.txt"); # /tmp/baz/bam.txt
758
759       Returns a new "Path::Tiny" object relative to the parent of the
760       original.  This is slightly more efficient than
761       "$path->parent->child(...)".
762
763       Current API available since 0.058.
764
765   size, size_human
766           my $p = path("foo"); # with size 1025 bytes
767
768           $p->size;                            # "1025"
769           $p->size_human;                      # "1.1 K"
770           $p->size_human( {format => "iec"} ); # "1.1 KiB"
771
772       Returns the size of a file.  The "size" method is just a wrapper around
773       "-s".
774
775       The "size_human" method provides a human-readable string similar to "ls
776       -lh".  Like "ls", it rounds upwards and provides one decimal place for
777       single-digit sizes and no decimal places for larger sizes.  The only
778       available option is "format", which has three valid values:
779
780       •   'ls' (the default): base-2 sizes, with "ls" style single-letter
781           suffixes (K, M, etc.)
782
783       •   'iec': base-2 sizes, with IEC binary suffixes (KiB, MiB, etc.)
784
785       •   'si': base-10 sizes, with SI decimal suffixes (kB, MB, etc.)
786
787       If "-s" would return "undef", "size_human" returns the empty string.
788
789       Current API available since 0.122.
790
791   slurp, slurp_raw, slurp_utf8
792           $data = path("foo.txt")->slurp;
793           $data = path("foo.txt")->slurp( {binmode => ":raw"} );
794           $data = path("foo.txt")->slurp_raw;
795           $data = path("foo.txt")->slurp_utf8;
796
797       Reads file contents into a scalar.  Takes an optional hash reference
798       which may be used to pass options.  The only available option is
799       "binmode", which is passed to "binmode()" on the handle used for
800       reading.
801
802       "slurp_raw" is like "slurp" with a "binmode" of ":unix" for a fast,
803       unbuffered, raw read.
804
805       "slurp_utf8" is like "slurp" with a "binmode" of
806       ":unix:encoding(UTF-8)" (or PerlIO::utf8_strict).  If Unicode::UTF8
807       0.58+ is installed, a raw slurp will be done instead and the result
808       decoded with "Unicode::UTF8".  This is just as strict and is roughly an
809       order of magnitude faster than using ":encoding(UTF-8)".
810
811       Note: "slurp" and friends lock the filehandle before slurping.  If you
812       plan to slurp from a file created with File::Temp, be sure to close
813       other handles or open without locking to avoid a deadlock:
814
815           my $tempfile = File::Temp->new(EXLOCK => 0);
816           my $guts = path($tempfile)->slurp;
817
818       Current API available since 0.004.
819
820   spew, spew_raw, spew_utf8
821           path("foo.txt")->spew(@data);
822           path("foo.txt")->spew(\@data);
823           path("foo.txt")->spew({binmode => ":raw"}, @data);
824           path("foo.txt")->spew_raw(@data);
825           path("foo.txt")->spew_utf8(@data);
826
827       Writes data to a file atomically.  The file is written to a temporary
828       file in the same directory, then renamed over the original.  An
829       optional hash reference may be used to pass options.  The only option
830       is "binmode", which is passed to "binmode()" on the handle used for
831       writing.
832
833       "spew_raw" is like "spew" with a "binmode" of ":unix" for a fast,
834       unbuffered, raw write.
835
836       "spew_utf8" is like "spew" with a "binmode" of ":unix:encoding(UTF-8)"
837       (or PerlIO::utf8_strict).  If Unicode::UTF8 0.58+ is installed, a raw
838       spew will be done instead on the data encoded with "Unicode::UTF8".
839
840       NOTE: because the file is written to a temporary file and then renamed,
841       the new file will wind up with permissions based on your current umask.
842       This is a feature to protect you from a race condition that would
843       otherwise give different permissions than you might expect.  If you
844       really want to keep the original mode flags, use "append" with the
845       "truncate" option.
846
847       Current API available since 0.011.
848
849   stat, lstat
850           $stat = path("foo.txt")->stat;
851           $stat = path("/some/symlink")->lstat;
852
853       Like calling "stat" or "lstat" from File::stat.
854
855       Current API available since 0.001.
856
857   stringify
858           $path = path("foo.txt");
859           say $path->stringify; # same as "$path"
860
861       Returns a string representation of the path.  Unlike "canonpath", this
862       method returns the path standardized with Unix-style "/" directory
863       separators.
864
865       Current API available since 0.001.
866
867   subsumes
868           path("foo/bar")->subsumes("foo/bar/baz"); # true
869           path("/foo/bar")->subsumes("/foo/baz");   # false
870
871       Returns true if the first path is a prefix of the second path at a
872       directory boundary.
873
874       This does not resolve parent directory entries ("..") or symlinks:
875
876           path("foo/bar")->subsumes("foo/bar/../baz"); # true
877
878       If such things are important to you, ensure that both paths are
879       resolved to the filesystem with "realpath":
880
881           my $p1 = path("foo/bar")->realpath;
882           my $p2 = path("foo/bar/../baz")->realpath;
883           if ( $p1->subsumes($p2) ) { ... }
884
885       Current API available since 0.048.
886
887   touch
888           path("foo.txt")->touch;
889           path("foo.txt")->touch($epoch_secs);
890
891       Like the Unix "touch" utility.  Creates the file if it doesn't exist,
892       or else changes the modification and access times to the current time.
893       If the first argument is the epoch seconds then it will be used.
894
895       Returns the path object so it can be easily chained with other methods:
896
897           # won't die if foo.txt doesn't exist
898           $content = path("foo.txt")->touch->slurp;
899
900       Current API available since 0.015.
901
902   touchpath
903           path("bar/baz/foo.txt")->touchpath;
904
905       Combines "mkpath" and "touch".  Creates the parent directory if it
906       doesn't exist, before touching the file.  Returns the path object like
907       "touch" does.
908
909       Current API available since 0.022.
910
911   visit
912           path("/tmp")->visit( \&callback, \%options );
913
914       Executes a callback for each child of a directory.  It returns a hash
915       reference with any state accumulated during iteration.
916
917       The options are the same as for "iterator" (which it uses internally):
918       "recurse" and "follow_symlinks".  Both default to false.
919
920       The callback function will receive a "Path::Tiny" object as the first
921       argument and a hash reference to accumulate state as the second
922       argument.  For example:
923
924           # collect files sizes
925           my $sizes = path("/tmp")->visit(
926               sub {
927                   my ($path, $state) = @_;
928                   return if $path->is_dir;
929                   $state->{$path} = -s $path;
930               },
931               { recurse => 1 }
932           );
933
934       For convenience, the "Path::Tiny" object will also be locally aliased
935       as the $_ global variable:
936
937           # print paths matching /foo/
938           path("/tmp")->visit( sub { say if /foo/ }, { recurse => 1} );
939
940       If the callback returns a reference to a false scalar value, iteration
941       will terminate.  This is not the same as "pruning" a directory search;
942       this just stops all iteration and returns the state hash reference.
943
944           # find up to 10 files larger than 100K
945           my $files = path("/tmp")->visit(
946               sub {
947                   my ($path, $state) = @_;
948                   $state->{$path}++ if -s $path > 102400
949                   return \0 if keys %$state == 10;
950               },
951               { recurse => 1 }
952           );
953
954       If you want more flexible iteration, use a module like
955       Path::Iterator::Rule.
956
957       Current API available since 0.062.
958
959   volume
960           $vol = path("/tmp/foo.txt")->volume;   # ""
961           $vol = path("C:/tmp/foo.txt")->volume; # "C:"
962
963       Returns the volume portion of the path.  This is equivalent to what
964       File::Spec would give from "splitpath" and thus usually is the empty
965       string on Unix-like operating systems or the drive letter for an
966       absolute path on "MSWin32".
967
968       Current API available since 0.001.
969

EXCEPTION HANDLING

971       Simple usage errors will generally croak.  Failures of underlying Perl
972       functions will be thrown as exceptions in the class
973       "Path::Tiny::Error".
974
975       A "Path::Tiny::Error" object will be a hash reference with the
976       following fields:
977
978       •   "op" — a description of the operation, usually function call and
979           any extra info
980
981       •   "file" — the file or directory relating to the error
982
983       •   "err" — hold $! at the time the error was thrown
984
985       •   "msg" — a string combining the above data and a Carp-like short
986           stack trace
987
988       Exception objects will stringify as the "msg" field.
989

ENVIRONMENT

991   PERL_PATH_TINY_NO_FLOCK
992       If the environment variable "PERL_PATH_TINY_NO_FLOCK" is set to a true
993       value then flock will NOT be used when accessing files (this is not
994       recommended).
995

CAVEATS

997   Subclassing not supported
998       For speed, this class is implemented as an array based object and uses
999       many direct function calls internally.  You must not subclass it and
1000       expect things to work properly.
1001
1002   File locking
1003       If flock is not supported on a platform, it will not be used, even if
1004       locking is requested.
1005
1006       In situations where a platform normally would support locking, but the
1007       flock fails due to a filesystem limitation, Path::Tiny has some
1008       heuristics to detect this and will warn once and continue in an unsafe
1009       mode.  If you want this failure to be fatal, you can fatalize the
1010       'flock' warnings category:
1011
1012           use warnings FATAL => 'flock';
1013
1014       See additional caveats below.
1015
1016       NFS and BSD
1017
1018       On BSD, Perl's flock implementation may not work to lock files on an
1019       NFS filesystem.  If detected, this situation will warn once, as
1020       described above.
1021
1022       Lustre
1023
1024       The Lustre filesystem does not support flock.  If detected, this
1025       situation will warn once, as described above.
1026
1027       AIX and locking
1028
1029       AIX requires a write handle for locking.  Therefore, calls that
1030       normally open a read handle and take a shared lock instead will open a
1031       read-write handle and take an exclusive lock.  If the user does not
1032       have write permission, no lock will be used.
1033
1034   utf8 vs UTF-8
1035       All the *_utf8 methods by default use ":encoding(UTF-8)" -- either as
1036       ":unix:encoding(UTF-8)" (unbuffered) or ":raw:encoding(UTF-8)"
1037       (buffered) -- which is strict against the Unicode spec and disallows
1038       illegal Unicode codepoints or UTF-8 sequences.
1039
1040       Unfortunately, ":encoding(UTF-8)" is very, very slow.  If you install
1041       Unicode::UTF8 0.58 or later, that module will be used by some *_utf8
1042       methods to encode or decode data after a raw, binary input/output
1043       operation, which is much faster.  Alternatively, if you install
1044       PerlIO::utf8_strict, that will be used instead of ":encoding(UTF-8)"
1045       and is also very fast.
1046
1047       If you need the performance and can accept the security risk,
1048       "slurp({binmode => ":unix:utf8"})" will be faster than
1049       ":unix:encoding(UTF-8)" (but not as fast as "Unicode::UTF8").
1050
1051       Note that the *_utf8 methods read in raw mode.  There is no CRLF
1052       translation on Windows.  If you must have CRLF translation, use the
1053       regular input/output methods with an appropriate binmode:
1054
1055         $path->spew_utf8($data);                            # raw
1056         $path->spew({binmode => ":encoding(UTF-8)"}, $data; # LF -> CRLF
1057
1058   Default IO layers and the open pragma
1059       If you have Perl 5.10 or later, file input/output methods ("slurp",
1060       "spew", etc.) and high-level handle opening methods ( "filehandle",
1061       "openr", "openw", etc. ) respect default encodings set by the "-C"
1062       switch or lexical open settings of the caller.  For UTF-8, this is
1063       almost certainly slower than using the dedicated "_utf8" methods if you
1064       have Unicode::UTF8.
1065

TYPE CONSTRAINTS AND COERCION

1067       A standard MooseX::Types library is available at
1068       MooseX::Types::Path::Tiny.  A Type::Tiny equivalent is available as
1069       Types::Path::Tiny.
1070

SEE ALSO

1072       These are other file/path utilities, which may offer a different
1073       feature set than "Path::Tiny".
1074
1075       •   File::chmod
1076
1077       •   File::Fu
1078
1079       •   IO::All
1080
1081       •   Path::Class
1082
1083       These iterators may be slightly faster than the recursive iterator in
1084       "Path::Tiny":
1085
1086       •   Path::Iterator::Rule
1087
1088       •   File::Next
1089
1090       There are probably comparable, non-Tiny tools.  Let me know if you want
1091       me to add a module to the list.
1092
1093       This module was featured in the 2013 Perl Advent Calendar
1094       <http://www.perladvent.org/2013/2013-12-18.html>.
1095

SUPPORT

1097   Bugs / Feature Requests
1098       Please report any bugs or feature requests through the issue tracker at
1099       <https://github.com/dagolden/Path-Tiny/issues>.  You will be notified
1100       automatically of any progress on your issue.
1101
1102   Source Code
1103       This is open source software.  The code repository is available for
1104       public review and contribution under the terms of the license.
1105
1106       <https://github.com/dagolden/Path-Tiny>
1107
1108         git clone https://github.com/dagolden/Path-Tiny.git
1109

AUTHOR

1111       David Golden <dagolden@cpan.org>
1112

CONTRIBUTORS

1114       •   Alex Efros <powerman@powerman.name>
1115
1116       •   Aristotle Pagaltzis <pagaltzis@gmx.de>
1117
1118       •   Chris Williams <bingos@cpan.org>
1119
1120       •   Dan Book <grinnz@grinnz.com>
1121
1122       •   Dave Rolsky <autarch@urth.org>
1123
1124       •   David Steinbrunner <dsteinbrunner@pobox.com>
1125
1126       •   Doug Bell <madcityzen@gmail.com>
1127
1128       •   Flavio Poletti <flavio@polettix.it>
1129
1130       •   Gabor Szabo <szabgab@cpan.org>
1131
1132       •   Gabriel Andrade <gabiruh@gmail.com>
1133
1134       •   George Hartzell <hartzell@cpan.org>
1135
1136       •   Geraud Continsouzas <geraud@scsi.nc>
1137
1138       •   Goro Fuji <gfuji@cpan.org>
1139
1140       •   Graham Knop <haarg@haarg.org>
1141
1142       •   Graham Ollis <plicease@cpan.org>
1143
1144       •   Ian Sillitoe <ian@sillit.com>
1145
1146       •   James Hunt <james@niftylogic.com>
1147
1148       •   John Karr <brainbuz@brainbuz.org>
1149
1150       •   Karen Etheridge <ether@cpan.org>
1151
1152       •   Mark Ellis <mark.ellis@cartridgesave.co.uk>
1153
1154       •   Martin H. Sluka <fany@cpan.org>
1155
1156       •   Martin Kjeldsen <mk@bluepipe.dk>
1157
1158       •   Michael G. Schwern <mschwern@cpan.org>
1159
1160       •   Nigel Gregoire <nigelgregoire@gmail.com>
1161
1162       •   Philippe Bruhat (BooK) <book@cpan.org>
1163
1164       •   regina-verbae <regina-verbae@users.noreply.github.com>
1165
1166       •   Roy Ivy III <rivy@cpan.org>
1167
1168       •   Shlomi Fish <shlomif@shlomifish.org>
1169
1170       •   Smylers <Smylers@stripey.com>
1171
1172       •   Tatsuhiko Miyagawa <miyagawa@bulknews.net>
1173
1174       •   Toby Inkster <tobyink@cpan.org>
1175
1176       •   Yanick Champoux <yanick@babyl.dyndns.org>
1177
1178       •   김도형 - Keedi Kim <keedi@cpan.org>
1179
1181       This software is Copyright (c) 2014 by David Golden.
1182
1183       This is free software, licensed under:
1184
1185         The Apache License, Version 2.0, January 2004
1186
1187
1188
1189perl v5.34.0                      2022-01-21                     Path::Tiny(3)
Impressum