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.108
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 = tempfile( @options ); # optional export
157           $temp = tempdir( @options );  # optional export
158
159       "tempfile" passes the options to "File::Temp->new" and returns a
160       "Path::Tiny" object with the file name.  The "TMPDIR" option is enabled
161       by default.
162
163       The resulting "File::Temp" object is cached. When the "Path::Tiny"
164       object is destroyed, the "File::Temp" object will be as well.
165
166       "File::Temp" annoyingly requires you to specify a custom template in
167       slightly different ways depending on which function or method you call,
168       but "Path::Tiny" lets you ignore that and can take either a leading
169       template or a "TEMPLATE" option and does the right thing.
170
171           $temp = Path::Tiny->tempfile( "customXXXXXXXX" );             # ok
172           $temp = Path::Tiny->tempfile( TEMPLATE => "customXXXXXXXX" ); # ok
173
174       The tempfile path object will be normalized to have an absolute path,
175       even if created in a relative directory using "DIR".  If you want it to
176       have the "realpath" instead, pass a leading options hash like this:
177
178           $real_temp = tempfile({realpath => 1}, @options);
179
180       "tempdir" is just like "tempfile", except it calls "File::Temp->newdir"
181       instead.
182
183       Both "tempfile" and "tempdir" may be exported on request and used as
184       functions instead of as methods.
185
186       Note: for tempfiles, the filehandles from File::Temp are closed and not
187       reused.  This is not as secure as using File::Temp handles directly,
188       but is less prone to deadlocks or access problems on some platforms.
189       Think of what "Path::Tiny" gives you to be just a temporary file name
190       that gets cleaned up.
191
192       Note 2: if you don't want these cleaned up automatically when the
193       object is destroyed, File::Temp requires different options for
194       directories and files.  Use "CLEANUP => 0" for directories and "UNLINK
195       => 0" for files.
196
197       Note 3: Don't lose the temporary object by chaining a method call
198       instead of storing it:
199
200           my $lost = tempdir()->child("foo"); # tempdir cleaned up right away
201
202       Note 4: The cached object may be accessed with the "cached_temp"
203       method.  Keeping a reference to, or modifying the cached object may
204       break the behavior documented above and is not supported.  Use at your
205       own risk.
206
207       Current API available since 0.097.
208

METHODS

210   absolute
211           $abs = path("foo/bar")->absolute;
212           $abs = path("foo/bar")->absolute("/tmp");
213
214       Returns a new "Path::Tiny" object with an absolute path (or itself if
215       already absolute).  If no argument is given, the current directory is
216       used as the absolute base path.  If an argument is given, it will be
217       converted to an absolute path (if it is not already) and used as the
218       absolute base path.
219
220       This will not resolve upward directories ("foo/../bar") unless
221       "canonpath" in File::Spec would normally do so on your platform.  If
222       you need them resolved, you must call the more expensive "realpath"
223       method instead.
224
225       On Windows, an absolute path without a volume component will have it
226       added based on the current drive.
227
228       Current API available since 0.101.
229
230   append, append_raw, append_utf8
231           path("foo.txt")->append(@data);
232           path("foo.txt")->append(\@data);
233           path("foo.txt")->append({binmode => ":raw"}, @data);
234           path("foo.txt")->append_raw(@data);
235           path("foo.txt")->append_utf8(@data);
236
237       Appends data to a file.  The file is locked with "flock" prior to
238       writing and closed afterwards.  An optional hash reference may be used
239       to pass options.  Valid options are:
240
241       ·   "binmode": passed to "binmode()" on the handle used for writing.
242
243       ·   "truncate": truncates the file after locking and before appending
244
245       The "truncate" option is a way to replace the contents of a file in
246       place, unlike "spew" which writes to a temporary file and then replaces
247       the original (if it exists).
248
249       "append_raw" is like "append" with a "binmode" of ":unix" for fast,
250       unbuffered, raw write.
251
252       "append_utf8" is like "append" with a "binmode" of
253       ":unix:encoding(UTF-8)" (or PerlIO::utf8_strict).  If Unicode::UTF8
254       0.58+ is installed, a raw append will be done instead on the data
255       encoded with "Unicode::UTF8".
256
257       Current API available since 0.060.
258
259   assert
260           $path = path("foo.txt")->assert( sub { $_->exists } );
261
262       Returns the invocant after asserting that a code reference argument
263       returns true.  When the assertion code reference runs, it will have the
264       invocant object in the $_ variable.  If it returns false, an exception
265       will be thrown.  The assertion code reference may also throw its own
266       exception.
267
268       If no assertion is provided, the invocant is returned without error.
269
270       Current API available since 0.062.
271
272   basename
273           $name = path("foo/bar.txt")->basename;        # bar.txt
274           $name = path("foo.txt")->basename('.txt');    # foo
275           $name = path("foo.txt")->basename(qr/.txt/);  # foo
276           $name = path("foo.txt")->basename(@suffixes);
277
278       Returns the file portion or last directory portion of a path.
279
280       Given a list of suffixes as strings or regular expressions, any that
281       match at the end of the file portion or last directory portion will be
282       removed before the result is returned.
283
284       Current API available since 0.054.
285
286   canonpath
287           $canonical = path("foo/bar")->canonpath; # foo\bar on Windows
288
289       Returns a string with the canonical format of the path name for the
290       platform.  In particular, this means directory separators will be "\"
291       on Windows.
292
293       Current API available since 0.001.
294
295   cached_temp
296       Returns the cached "File::Temp" or "File::Temp::Dir" object if the
297       "Path::Tiny" object was created with "/tempfile" or "/tempdir".  If
298       there is no such object, this method throws.
299
300       WARNING: Keeping a reference to, or modifying the cached object may
301       break the behavior documented for temporary files and directories
302       created with "Path::Tiny" and is not supported.  Use at your own risk.
303
304       Current API available since 0.101.
305
306   child
307           $file = path("/tmp")->child("foo.txt"); # "/tmp/foo.txt"
308           $file = path("/tmp")->child(@parts);
309
310       Returns a new "Path::Tiny" object relative to the original.  Works like
311       "catfile" or "catdir" from File::Spec, but without caring about file or
312       directories.
313
314       WARNING: because the argument could contain ".." or refer to symlinks,
315       there is no guarantee that the new path refers to an actual descendent
316       of the original.  If this is important to you, transform parent and
317       child with "realpath" and check them with "subsumes".
318
319       Current API available since 0.001.
320
321   children
322           @paths = path("/tmp")->children;
323           @paths = path("/tmp")->children( qr/\.txt$/ );
324
325       Returns a list of "Path::Tiny" objects for all files and directories
326       within a directory.  Excludes "." and ".." automatically.
327
328       If an optional "qr//" argument is provided, it only returns objects for
329       child names that match the given regular expression.  Only the base
330       name is used for matching:
331
332           @paths = path("/tmp")->children( qr/^foo/ );
333           # matches children like the glob foo*
334
335       Current API available since 0.028.
336
337   chmod
338           path("foo.txt")->chmod(0777);
339           path("foo.txt")->chmod("0755");
340           path("foo.txt")->chmod("go-w");
341           path("foo.txt")->chmod("a=r,u+wx");
342
343       Sets file or directory permissions.  The argument can be a numeric
344       mode, a octal string beginning with a "0" or a limited subset of the
345       symbolic mode use by /bin/chmod.
346
347       The symbolic mode must be a comma-delimited list of mode clauses.
348       Clauses must match "qr/\A([augo]+)([=+-])([rwx]+)\z/", which defines
349       "who", "op" and "perms" parameters for each clause.  Unlike /bin/chmod,
350       all three parameters are required for each clause, multiple ops are not
351       allowed and permissions "stugoX" are not supported.  (See File::chmod
352       for more complex needs.)
353
354       Current API available since 0.053.
355
356   copy
357           path("/tmp/foo.txt")->copy("/tmp/bar.txt");
358
359       Copies the current path to the given destination using File::Copy's
360       "copy" function. Upon success, returns the "Path::Tiny" object for the
361       newly copied file.
362
363       Current API available since 0.070.
364
365   digest
366           $obj = path("/tmp/foo.txt")->digest;        # SHA-256
367           $obj = path("/tmp/foo.txt")->digest("MD5"); # user-selected
368           $obj = path("/tmp/foo.txt")->digest( { chunk_size => 1e6 }, "MD5" );
369
370       Returns a hexadecimal digest for a file.  An optional hash reference of
371       options may be given.  The only option is "chunk_size".  If
372       "chunk_size" is given, that many bytes will be read at a time.  If not
373       provided, the entire file will be slurped into memory to compute the
374       digest.
375
376       Any subsequent arguments are passed to the constructor for Digest to
377       select an algorithm.  If no arguments are given, the default is
378       SHA-256.
379
380       Current API available since 0.056.
381
382   dirname (deprecated)
383           $name = path("/tmp/foo.txt")->dirname; # "/tmp/"
384
385       Returns the directory portion you would get from calling
386       "File::Spec->splitpath( $path->stringify )" or "." for a path without a
387       parent directory portion.  Because File::Spec is inconsistent, the
388       result might or might not have a trailing slash.  Because of this, this
389       method is deprecated.
390
391       A better, more consistently approach is likely
392       "$path->parent->stringify", which will not have a trailing slash except
393       for a root directory.
394
395       Deprecated in 0.056.
396
397   edit, edit_raw, edit_utf8
398           path("foo.txt")->edit( \&callback, $options );
399           path("foo.txt")->edit_utf8( \&callback );
400           path("foo.txt")->edit_raw( \&callback );
401
402       These are convenience methods that allow "editing" a file using a
403       single callback argument. They slurp the file using "slurp", place the
404       contents inside a localized $_ variable, call the callback function
405       (without arguments), and then write $_ (presumably mutated) back to the
406       file with "spew".
407
408       An optional hash reference may be used to pass options.  The only
409       option is "binmode", which is passed to "slurp" and "spew".
410
411       "edit_utf8" and "edit_raw" act like their respective "slurp_*" and
412       "spew_*" methods.
413
414       Current API available since 0.077.
415
416   edit_lines, edit_lines_utf8, edit_lines_raw
417           path("foo.txt")->edit_lines( \&callback, $options );
418           path("foo.txt")->edit_lines_utf8( \&callback );
419           path("foo.txt")->edit_lines_raw( \&callback );
420
421       These are convenience methods that allow "editing" a file's lines using
422       a single callback argument.  They iterate over the file: for each line,
423       the line is put into a localized $_ variable, the callback function is
424       executed (without arguments) and then $_ is written to a temporary
425       file.  When iteration is finished, the temporary file is atomically
426       renamed over the original.
427
428       An optional hash reference may be used to pass options.  The only
429       option is "binmode", which is passed to the method that open handles
430       for reading and writing.
431
432       "edit_lines_utf8" and "edit_lines_raw" act like their respective
433       "slurp_*" and "spew_*" methods.
434
435       Current API available since 0.077.
436
437   exists, is_file, is_dir
438           if ( path("/tmp")->exists ) { ... }     # -e
439           if ( path("/tmp")->is_dir ) { ... }     # -d
440           if ( path("/tmp")->is_file ) { ... }    # -e && ! -d
441
442       Implements file test operations, this means the file or directory
443       actually has to exist on the filesystem.  Until then, it's just a path.
444
445       Note: "is_file" is not "-f" because "-f" is not the opposite of "-d".
446       "-f" means "plain file", excluding symlinks, devices, etc. that often
447       can be read just like files.
448
449       Use "-f" instead if you really mean to check for a plain file.
450
451       Current API available since 0.053.
452
453   filehandle
454           $fh = path("/tmp/foo.txt")->filehandle($mode, $binmode);
455           $fh = path("/tmp/foo.txt")->filehandle({ locked => 1 }, $mode, $binmode);
456           $fh = path("/tmp/foo.txt")->filehandle({ exclusive => 1  }, $mode, $binmode);
457
458       Returns an open file handle.  The $mode argument must be a Perl-style
459       read/write mode string ("<" ,">", ">>", etc.).  If a $binmode is given,
460       it is set during the "open" call.
461
462       An optional hash reference may be used to pass options.
463
464       The "locked" option governs file locking; if true, handles opened for
465       writing, appending or read-write are locked with "LOCK_EX"; otherwise,
466       they are locked with "LOCK_SH".  When using "locked", ">" or "+>" modes
467       will delay truncation until after the lock is acquired.
468
469       The "exclusive" option causes the open() call to fail if the file
470       already exists.  This corresponds to the O_EXCL flag to sysopen /
471       open(2).  "exclusive" implies "locked" and will set it for you if you
472       forget it.
473
474       See "openr", "openw", "openrw", and "opena" for sugar.
475
476       Current API available since 0.066.
477
478   is_absolute, is_relative
479           if ( path("/tmp")->is_absolute ) { ... }
480           if ( path("/tmp")->is_relative ) { ... }
481
482       Booleans for whether the path appears absolute or relative.
483
484       Current API available since 0.001.
485
486   is_rootdir
487           while ( ! $path->is_rootdir ) {
488               $path = $path->parent;
489               ...
490           }
491
492       Boolean for whether the path is the root directory of the volume.  I.e.
493       the "dirname" is "q[/]" and the "basename" is "q[]".
494
495       This works even on "MSWin32" with drives and UNC volumes:
496
497           path("C:/")->is_rootdir;             # true
498           path("//server/share/")->is_rootdir; #true
499
500       Current API available since 0.038.
501
502   iterator
503           $iter = path("/tmp")->iterator( \%options );
504
505       Returns a code reference that walks a directory lazily.  Each
506       invocation returns a "Path::Tiny" object or undef when the iterator is
507       exhausted.
508
509           $iter = path("/tmp")->iterator;
510           while ( $path = $iter->() ) {
511               ...
512           }
513
514       The current and parent directory entries ("." and "..") will not be
515       included.
516
517       If the "recurse" option is true, the iterator will walk the directory
518       recursively, breadth-first.  If the "follow_symlinks" option is also
519       true, directory links will be followed recursively.  There is no
520       protection against loops when following links. If a directory is not
521       readable, it will not be followed.
522
523       The default is the same as:
524
525           $iter = path("/tmp")->iterator( {
526               recurse         => 0,
527               follow_symlinks => 0,
528           } );
529
530       For a more powerful, recursive iterator with built-in loop avoidance,
531       see Path::Iterator::Rule.
532
533       See also "visit".
534
535       Current API available since 0.016.
536
537   lines, lines_raw, lines_utf8
538           @contents = path("/tmp/foo.txt")->lines;
539           @contents = path("/tmp/foo.txt")->lines(\%options);
540           @contents = path("/tmp/foo.txt")->lines_raw;
541           @contents = path("/tmp/foo.txt")->lines_utf8;
542
543           @contents = path("/tmp/foo.txt")->lines( { chomp => 1, count => 4 } );
544
545       Returns a list of lines from a file.  Optionally takes a hash-reference
546       of options.  Valid options are "binmode", "count" and "chomp".
547
548       If "binmode" is provided, it will be set on the handle prior to
549       reading.
550
551       If a positive "count" is provided, that many lines will be returned
552       from the start of the file.  If a negative "count" is provided, the
553       entire file will be read, but only "abs(count)" will be kept and
554       returned.  If "abs(count)" exceeds the number of lines in the file, all
555       lines will be returned.
556
557       If "chomp" is set, any end-of-line character sequences ("CR", "CRLF",
558       or "LF") will be removed from the lines returned.
559
560       Because the return is a list, "lines" in scalar context will return the
561       number of lines (and throw away the data).
562
563           $number_of_lines = path("/tmp/foo.txt")->lines;
564
565       "lines_raw" is like "lines" with a "binmode" of ":raw".  We use ":raw"
566       instead of ":unix" so PerlIO buffering can manage reading by line.
567
568       "lines_utf8" is like "lines" with a "binmode" of ":raw:encoding(UTF-8)"
569       (or PerlIO::utf8_strict).  If Unicode::UTF8 0.58+ is installed, a raw
570       UTF-8 slurp will be done and then the lines will be split.  This is
571       actually faster than relying on ":encoding(UTF-8)", though a bit memory
572       intensive.  If memory use is a concern, consider "openr_utf8" and
573       iterating directly on the handle.
574
575       Current API available since 0.065.
576
577   mkpath
578           path("foo/bar/baz")->mkpath;
579           path("foo/bar/baz")->mkpath( \%options );
580
581       Like calling "make_path" from File::Path.  An optional hash reference
582       is passed through to "make_path".  Errors will be trapped and an
583       exception thrown.  Returns the list of directories created or an empty
584       list if the directories already exist, just like "make_path".
585
586       Current API available since 0.001.
587
588   move
589           path("foo.txt")->move("bar.txt");
590
591       Move the current path to the given destination path using Perl's built-
592       in rename function. Returns the result of the "rename" function (except
593       it throws an exception if it fails).
594
595       Current API available since 0.001.
596
597   openr, openw, openrw, opena
598           $fh = path("foo.txt")->openr($binmode);  # read
599           $fh = path("foo.txt")->openr_raw;
600           $fh = path("foo.txt")->openr_utf8;
601
602           $fh = path("foo.txt")->openw($binmode);  # write
603           $fh = path("foo.txt")->openw_raw;
604           $fh = path("foo.txt")->openw_utf8;
605
606           $fh = path("foo.txt")->opena($binmode);  # append
607           $fh = path("foo.txt")->opena_raw;
608           $fh = path("foo.txt")->opena_utf8;
609
610           $fh = path("foo.txt")->openrw($binmode); # read/write
611           $fh = path("foo.txt")->openrw_raw;
612           $fh = path("foo.txt")->openrw_utf8;
613
614       Returns a file handle opened in the specified mode.  The "openr" style
615       methods take a single "binmode" argument.  All of the "open*" methods
616       have "open*_raw" and "open*_utf8" equivalents that use ":raw" and
617       ":raw:encoding(UTF-8)", respectively.
618
619       An optional hash reference may be used to pass options.  The only
620       option is "locked".  If true, handles opened for writing, appending or
621       read-write are locked with "LOCK_EX"; otherwise, they are locked for
622       "LOCK_SH".
623
624           $fh = path("foo.txt")->openrw_utf8( { locked => 1 } );
625
626       See "filehandle" for more on locking.
627
628       Current API available since 0.011.
629
630   parent
631           $parent = path("foo/bar/baz")->parent; # foo/bar
632           $parent = path("foo/wibble.txt")->parent; # foo
633
634           $parent = path("foo/bar/baz")->parent(2); # foo
635
636       Returns a "Path::Tiny" object corresponding to the parent directory of
637       the original directory or file. An optional positive integer argument
638       is the number of parent directories upwards to return.  "parent" by
639       itself is equivalent to parent(1).
640
641       Current API available since 0.014.
642
643   realpath
644           $real = path("/baz/foo/../bar")->realpath;
645           $real = path("foo/../bar")->realpath;
646
647       Returns a new "Path::Tiny" object with all symbolic links and upward
648       directory parts resolved using Cwd's "realpath".  Compared to
649       "absolute", this is more expensive as it must actually consult the
650       filesystem.
651
652       If the parent path can't be resolved (e.g. if it includes directories
653       that don't exist), an exception will be thrown:
654
655           $real = path("doesnt_exist/foo")->realpath; # dies
656
657       However, if the parent path exists and only the last component (e.g.
658       filename) doesn't exist, the realpath will be the realpath of the
659       parent plus the non-existent last component:
660
661           $real = path("./aasdlfasdlf")->realpath; # works
662
663       The underlying Cwd module usually worked this way on Unix, but died on
664       Windows (and some Unixes) if the full path didn't exist.  As of version
665       0.064, it's safe to use anywhere.
666
667       Current API available since 0.001.
668
669   relative
670           $rel = path("/tmp/foo/bar")->relative("/tmp"); # foo/bar
671
672       Returns a "Path::Tiny" object with a path relative to a new base path
673       given as an argument.  If no argument is given, the current directory
674       will be used as the new base path.
675
676       If either path is already relative, it will be made absolute based on
677       the current directly before determining the new relative path.
678
679       The algorithm is roughly as follows:
680
681       ·   If the original and new base path are on different volumes, an
682           exception will be thrown.
683
684       ·   If the original and new base are identical, the relative path is
685           ".".
686
687       ·   If the new base subsumes the original, the relative path is the
688           original path with the new base chopped off the front
689
690       ·   If the new base does not subsume the original, a common prefix path
691           is determined (possibly the root directory) and the relative path
692           will consist of updirs ("..") to reach the common prefix, followed
693           by the original path less the common prefix.
694
695       Unlike "File::Spec::abs2rel", in the last case above, the calculation
696       based on a common prefix takes into account symlinks that could affect
697       the updir process.  Given an original path "/A/B" and a new base
698       "/A/C", (where "A", "B" and "C" could each have multiple path
699       components):
700
701       ·   Symlinks in "A" don't change the result unless the last component
702           of A is a symlink and the first component of "C" is an updir.
703
704       ·   Symlinks in "B" don't change the result and will exist in the
705           result as given.
706
707       ·   Symlinks and updirs in "C" must be resolved to actual paths, taking
708           into account the possibility that not all path components might
709           exist on the filesystem.
710
711       Current API available since 0.001.  New algorithm (that accounts for
712       symlinks) available since 0.079.
713
714   remove
715           path("foo.txt")->remove;
716
717       This is just like "unlink", except for its error handling: if the path
718       does not exist, it returns false; if deleting the file fails, it throws
719       an exception.
720
721       Current API available since 0.012.
722
723   remove_tree
724           # directory
725           path("foo/bar/baz")->remove_tree;
726           path("foo/bar/baz")->remove_tree( \%options );
727           path("foo/bar/baz")->remove_tree( { safe => 0 } ); # force remove
728
729       Like calling "remove_tree" from File::Path, but defaults to "safe"
730       mode.  An optional hash reference is passed through to "remove_tree".
731       Errors will be trapped and an exception thrown.  Returns the number of
732       directories deleted, just like "remove_tree".
733
734       If you want to remove a directory only if it is empty, use the built-in
735       "rmdir" function instead.
736
737           rmdir path("foo/bar/baz/");
738
739       Current API available since 0.013.
740
741   sibling
742           $foo = path("/tmp/foo.txt");
743           $sib = $foo->sibling("bar.txt");        # /tmp/bar.txt
744           $sib = $foo->sibling("baz", "bam.txt"); # /tmp/baz/bam.txt
745
746       Returns a new "Path::Tiny" object relative to the parent of the
747       original.  This is slightly more efficient than
748       "$path->parent->child(...)".
749
750       Current API available since 0.058.
751
752   slurp, slurp_raw, slurp_utf8
753           $data = path("foo.txt")->slurp;
754           $data = path("foo.txt")->slurp( {binmode => ":raw"} );
755           $data = path("foo.txt")->slurp_raw;
756           $data = path("foo.txt")->slurp_utf8;
757
758       Reads file contents into a scalar.  Takes an optional hash reference
759       which may be used to pass options.  The only available option is
760       "binmode", which is passed to "binmode()" on the handle used for
761       reading.
762
763       "slurp_raw" is like "slurp" with a "binmode" of ":unix" for a fast,
764       unbuffered, raw read.
765
766       "slurp_utf8" is like "slurp" with a "binmode" of
767       ":unix:encoding(UTF-8)" (or PerlIO::utf8_strict).  If Unicode::UTF8
768       0.58+ is installed, a raw slurp will be done instead and the result
769       decoded with "Unicode::UTF8".  This is just as strict and is roughly an
770       order of magnitude faster than using ":encoding(UTF-8)".
771
772       Note: "slurp" and friends lock the filehandle before slurping.  If you
773       plan to slurp from a file created with File::Temp, be sure to close
774       other handles or open without locking to avoid a deadlock:
775
776           my $tempfile = File::Temp->new(EXLOCK => 0);
777           my $guts = path($tempfile)->slurp;
778
779       Current API available since 0.004.
780
781   spew, spew_raw, spew_utf8
782           path("foo.txt")->spew(@data);
783           path("foo.txt")->spew(\@data);
784           path("foo.txt")->spew({binmode => ":raw"}, @data);
785           path("foo.txt")->spew_raw(@data);
786           path("foo.txt")->spew_utf8(@data);
787
788       Writes data to a file atomically.  The file is written to a temporary
789       file in the same directory, then renamed over the original.  An
790       optional hash reference may be used to pass options.  The only option
791       is "binmode", which is passed to "binmode()" on the handle used for
792       writing.
793
794       "spew_raw" is like "spew" with a "binmode" of ":unix" for a fast,
795       unbuffered, raw write.
796
797       "spew_utf8" is like "spew" with a "binmode" of ":unix:encoding(UTF-8)"
798       (or PerlIO::utf8_strict).  If Unicode::UTF8 0.58+ is installed, a raw
799       spew will be done instead on the data encoded with "Unicode::UTF8".
800
801       NOTE: because the file is written to a temporary file and then renamed,
802       the new file will wind up with permissions based on your current umask.
803       This is a feature to protect you from a race condition that would
804       otherwise give different permissions than you might expect.  If you
805       really want to keep the original mode flags, use "append" with the
806       "truncate" option.
807
808       Current API available since 0.011.
809
810   stat, lstat
811           $stat = path("foo.txt")->stat;
812           $stat = path("/some/symlink")->lstat;
813
814       Like calling "stat" or "lstat" from File::stat.
815
816       Current API available since 0.001.
817
818   stringify
819           $path = path("foo.txt");
820           say $path->stringify; # same as "$path"
821
822       Returns a string representation of the path.  Unlike "canonpath", this
823       method returns the path standardized with Unix-style "/" directory
824       separators.
825
826       Current API available since 0.001.
827
828   subsumes
829           path("foo/bar")->subsumes("foo/bar/baz"); # true
830           path("/foo/bar")->subsumes("/foo/baz");   # false
831
832       Returns true if the first path is a prefix of the second path at a
833       directory boundary.
834
835       This does not resolve parent directory entries ("..") or symlinks:
836
837           path("foo/bar")->subsumes("foo/bar/../baz"); # true
838
839       If such things are important to you, ensure that both paths are
840       resolved to the filesystem with "realpath":
841
842           my $p1 = path("foo/bar")->realpath;
843           my $p2 = path("foo/bar/../baz")->realpath;
844           if ( $p1->subsumes($p2) ) { ... }
845
846       Current API available since 0.048.
847
848   touch
849           path("foo.txt")->touch;
850           path("foo.txt")->touch($epoch_secs);
851
852       Like the Unix "touch" utility.  Creates the file if it doesn't exist,
853       or else changes the modification and access times to the current time.
854       If the first argument is the epoch seconds then it will be used.
855
856       Returns the path object so it can be easily chained with other methods:
857
858           # won't die if foo.txt doesn't exist
859           $content = path("foo.txt")->touch->slurp;
860
861       Current API available since 0.015.
862
863   touchpath
864           path("bar/baz/foo.txt")->touchpath;
865
866       Combines "mkpath" and "touch".  Creates the parent directory if it
867       doesn't exist, before touching the file.  Returns the path object like
868       "touch" does.
869
870       Current API available since 0.022.
871
872   visit
873           path("/tmp")->visit( \&callback, \%options );
874
875       Executes a callback for each child of a directory.  It returns a hash
876       reference with any state accumulated during iteration.
877
878       The options are the same as for "iterator" (which it uses internally):
879       "recurse" and "follow_symlinks".  Both default to false.
880
881       The callback function will receive a "Path::Tiny" object as the first
882       argument and a hash reference to accumulate state as the second
883       argument.  For example:
884
885           # collect files sizes
886           my $sizes = path("/tmp")->visit(
887               sub {
888                   my ($path, $state) = @_;
889                   return if $path->is_dir;
890                   $state->{$path} = -s $path;
891               },
892               { recurse => 1 }
893           );
894
895       For convenience, the "Path::Tiny" object will also be locally aliased
896       as the $_ global variable:
897
898           # print paths matching /foo/
899           path("/tmp")->visit( sub { say if /foo/ }, { recurse => 1} );
900
901       If the callback returns a reference to a false scalar value, iteration
902       will terminate.  This is not the same as "pruning" a directory search;
903       this just stops all iteration and returns the state hash reference.
904
905           # find up to 10 files larger than 100K
906           my $files = path("/tmp")->visit(
907               sub {
908                   my ($path, $state) = @_;
909                   $state->{$path}++ if -s $path > 102400
910                   return \0 if keys %$state == 10;
911               },
912               { recurse => 1 }
913           );
914
915       If you want more flexible iteration, use a module like
916       Path::Iterator::Rule.
917
918       Current API available since 0.062.
919
920   volume
921           $vol = path("/tmp/foo.txt")->volume;   # ""
922           $vol = path("C:/tmp/foo.txt")->volume; # "C:"
923
924       Returns the volume portion of the path.  This is equivalent to what
925       File::Spec would give from "splitpath" and thus usually is the empty
926       string on Unix-like operating systems or the drive letter for an
927       absolute path on "MSWin32".
928
929       Current API available since 0.001.
930

EXCEPTION HANDLING

932       Simple usage errors will generally croak.  Failures of underlying Perl
933       functions will be thrown as exceptions in the class
934       "Path::Tiny::Error".
935
936       A "Path::Tiny::Error" object will be a hash reference with the
937       following fields:
938
939       ·   "op" — a description of the operation, usually function call and
940           any extra info
941
942       ·   "file" — the file or directory relating to the error
943
944       ·   "err" — hold $! at the time the error was thrown
945
946       ·   "msg" — a string combining the above data and a Carp-like short
947           stack trace
948
949       Exception objects will stringify as the "msg" field.
950

ENVIRONMENT

952   PERL_PATH_TINY_NO_FLOCK
953       If the environment variable "PERL_PATH_TINY_NO_FLOCK" is set to a true
954       value then flock will NOT be used when accessing files (this is not
955       recommended).
956

CAVEATS

958   Subclassing not supported
959       For speed, this class is implemented as an array based object and uses
960       many direct function calls internally.  You must not subclass it and
961       expect things to work properly.
962
963   File locking
964       If flock is not supported on a platform, it will not be used, even if
965       locking is requested.
966
967       In situations where a platform normally would support locking, but the
968       flock fails due to a filesystem limitation, Path::Tiny has some
969       heuristics to detect this and will warn once and continue in an unsafe
970       mode.  If you want this failure to be fatal, you can fatalize the
971       'flock' warnings category:
972
973           use warnings FATAL => 'flock';
974
975       See additional caveats below.
976
977       NFS and BSD
978
979       On BSD, Perl's flock implementation may not work to lock files on an
980       NFS filesystem.  If detected, this situation will warn once, as
981       described above.
982
983       Lustre
984
985       The Lustre filesystem does not support flock.  If detected, this
986       situation will warn once, as described above.
987
988       AIX and locking
989
990       AIX requires a write handle for locking.  Therefore, calls that
991       normally open a read handle and take a shared lock instead will open a
992       read-write handle and take an exclusive lock.  If the user does not
993       have write permission, no lock will be used.
994
995   utf8 vs UTF-8
996       All the *_utf8 methods by default use ":encoding(UTF-8)" -- either as
997       ":unix:encoding(UTF-8)" (unbuffered) or ":raw:encoding(UTF-8)"
998       (buffered) -- which is strict against the Unicode spec and disallows
999       illegal Unicode codepoints or UTF-8 sequences.
1000
1001       Unfortunately, ":encoding(UTF-8)" is very, very slow.  If you install
1002       Unicode::UTF8 0.58 or later, that module will be used by some *_utf8
1003       methods to encode or decode data after a raw, binary input/output
1004       operation, which is much faster.  Alternatively, if you install
1005       PerlIO::utf8_strict, that will be used instead of ":encoding(UTF-8)"
1006       and is also very fast.
1007
1008       If you need the performance and can accept the security risk,
1009       "slurp({binmode => ":unix:utf8"})" will be faster than
1010       ":unix:encoding(UTF-8)" (but not as fast as "Unicode::UTF8").
1011
1012       Note that the *_utf8 methods read in raw mode.  There is no CRLF
1013       translation on Windows.  If you must have CRLF translation, use the
1014       regular input/output methods with an appropriate binmode:
1015
1016         $path->spew_utf8($data);                            # raw
1017         $path->spew({binmode => ":encoding(UTF-8)"}, $data; # LF -> CRLF
1018
1019   Default IO layers and the open pragma
1020       If you have Perl 5.10 or later, file input/output methods ("slurp",
1021       "spew", etc.) and high-level handle opening methods ( "filehandle",
1022       "openr", "openw", etc. ) respect default encodings set by the "-C"
1023       switch or lexical open settings of the caller.  For UTF-8, this is
1024       almost certainly slower than using the dedicated "_utf8" methods if you
1025       have Unicode::UTF8.
1026

TYPE CONSTRAINTS AND COERCION

1028       A standard MooseX::Types library is available at
1029       MooseX::Types::Path::Tiny.  A Type::Tiny equivalent is available as
1030       Types::Path::Tiny.
1031

SEE ALSO

1033       These are other file/path utilities, which may offer a different
1034       feature set than "Path::Tiny".
1035
1036       ·   File::chmod
1037
1038       ·   File::Fu
1039
1040       ·   IO::All
1041
1042       ·   Path::Class
1043
1044       These iterators may be slightly faster than the recursive iterator in
1045       "Path::Tiny":
1046
1047       ·   Path::Iterator::Rule
1048
1049       ·   File::Next
1050
1051       There are probably comparable, non-Tiny tools.  Let me know if you want
1052       me to add a module to the list.
1053
1054       This module was featured in the 2013 Perl Advent Calendar
1055       <http://www.perladvent.org/2013/2013-12-18.html>.
1056

SUPPORT

1058   Bugs / Feature Requests
1059       Please report any bugs or feature requests through the issue tracker at
1060       <https://github.com/dagolden/Path-Tiny/issues>.  You will be notified
1061       automatically of any progress on your issue.
1062
1063   Source Code
1064       This is open source software.  The code repository is available for
1065       public review and contribution under the terms of the license.
1066
1067       <https://github.com/dagolden/Path-Tiny>
1068
1069         git clone https://github.com/dagolden/Path-Tiny.git
1070

AUTHOR

1072       David Golden <dagolden@cpan.org>
1073

CONTRIBUTORS

1075       ·   Alex Efros <powerman@powerman.name>
1076
1077       ·   Aristotle Pagaltzis <pagaltzis@gmx.de>
1078
1079       ·   Chris Williams <bingos@cpan.org>
1080
1081       ·   Dave Rolsky <autarch@urth.org>
1082
1083       ·   David Steinbrunner <dsteinbrunner@pobox.com>
1084
1085       ·   Doug Bell <madcityzen@gmail.com>
1086
1087       ·   Gabor Szabo <szabgab@cpan.org>
1088
1089       ·   Gabriel Andrade <gabiruh@gmail.com>
1090
1091       ·   George Hartzell <hartzell@cpan.org>
1092
1093       ·   Geraud Continsouzas <geraud@scsi.nc>
1094
1095       ·   Goro Fuji <gfuji@cpan.org>
1096
1097       ·   Graham Knop <haarg@haarg.org>
1098
1099       ·   Graham Ollis <plicease@cpan.org>
1100
1101       ·   Ian Sillitoe <ian@sillit.com>
1102
1103       ·   James Hunt <james@niftylogic.com>
1104
1105       ·   John Karr <brainbuz@brainbuz.org>
1106
1107       ·   Karen Etheridge <ether@cpan.org>
1108
1109       ·   Mark Ellis <mark.ellis@cartridgesave.co.uk>
1110
1111       ·   Martin H. Sluka <fany@cpan.org>
1112
1113       ·   Martin Kjeldsen <mk@bluepipe.dk>
1114
1115       ·   Michael G. Schwern <mschwern@cpan.org>
1116
1117       ·   Nigel Gregoire <nigelgregoire@gmail.com>
1118
1119       ·   Philippe Bruhat (BooK) <book@cpan.org>
1120
1121       ·   Regina Verbae <regina-verbae@users.noreply.github.com>
1122
1123       ·   Roy Ivy III <rivy@cpan.org>
1124
1125       ·   Shlomi Fish <shlomif@shlomifish.org>
1126
1127       ·   Smylers <Smylers@stripey.com>
1128
1129       ·   Tatsuhiko Miyagawa <miyagawa@bulknews.net>
1130
1131       ·   Toby Inkster <tobyink@cpan.org>
1132
1133       ·   Yanick Champoux <yanick@babyl.dyndns.org>
1134
1135       ·   김도형 - Keedi Kim <keedi@cpan.org>
1136
1138       This software is Copyright (c) 2014 by David Golden.
1139
1140       This is free software, licensed under:
1141
1142         The Apache License, Version 2.0, January 2004
1143
1144
1145
1146perl v5.28.1                      2018-07-30                     Path::Tiny(3)
Impressum