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