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