Path::Tiny(3)
π Path::Tiny β the manual page, but make it make sense π
okay bestie, gather round, because this is Path::Tiny(3) β a User Contributed Perl Documentation page β and it's genuinely one of the good ones. no cap.
β¨ VERSION β¨
version 0.150 π
πΈ SYNOPSIS πΈ
use Path::Tiny;
# Creating Path::Tiny objects
my $dir = path("/tmp");
my $foo = path("foo.txt");
my $subdir = $dir->child("foo");
my $bar = $subdir->child("bar.txt");
# Stringifies as cleaned up path
my $file = path("./foo.txt");
print $file; # "foo.txt"
# Reading files
my $guts = $file->slurp;
$guts = $file->slurp_utf8;
my @lines = $file->lines;
@lines = $file->lines_utf8;
my ($head) = $file->lines( {count => 1} );
my ($tail) = $file->lines( {count => -1} );
# Writing files
$bar->spew( @data );
$bar->spew_utf8( @data );
# Reading directories
for ( $dir->children ) { ... }
my $iter = $dir->iterator;
while ( my $next = $iter->() ) { ... }
like... look at that. so clean. so tidy. it's giving file path utility and it's eating, honestly. π
π¦ DESCRIPTION π¦
So this module is a small, fast utility for working with file paths. It's way friendlier to use than File::Spec, and it gives you easy access to functions from a bunch of other core file handling modules. The whole goal is to be smaller and faster than a lot of the alternatives on CPAN, while helping you do a ton of common stuff in ways that are consistent and less error-prone. periodt.
Now, the honest part: Path::Tiny does not try to work for anything except Unix-like and Win32 platforms. And even then, it might break if you try something particularly obscure or tortuous. (Quick! What does this mean: ///../../..//./././a//b/.././c/././? And how does it differ on Win32? yeah. exactly. π)
All paths are forced to have Unix-style forward slashes. Stringifying the object gives you back the path (after some clean up).
File input/output methods flock handles before reading or writing, as appropriate (if supported by the platform and/or filesystem).
The *_utf8 methods (slurp_utf8, lines_utf8, etc.) operate in raw mode. On Windows, that means they will not have CRLF translation from the :crlf IO layer. Installing Unicode::UTF8 0.58 or later will speed up *_utf8 situations in many cases and is highly recommended. Alternatively, installing PerlIO::utf8_strict 0.003 or later will be used in place of the default :encoding(UTF-8).
This module depends heavily on PerlIO layers for correct operation and thus requires Perl 5.008001 or later. no ancient perls, sorry babe.
π CONSTRUCTORS π
β path
$path = path("foo/bar");
$path = path("/tmp", "file.txt"); # list
$path = path("."); # cwd
Constructs a Path::Tiny object. It genuinely does not matter if you give it a file path or a directory path β it's still up to you to call directory-like methods only on directories and file-like methods only on files. This function is exported automatically by default. π«Ά
The first argument must be defined and have non-zero length, or an exception will be thrown. This is a good thing, actually β it prevents subtle, dangerous errors with code like path( maybe_undef() )->remove_tree. like imagine. π
DEPRECATED: If and only if the first character of the first argument topathis a tilde (~), then tilde replacement will be applied to the first path segment. A single tilde will be replaced withglob('~')and a tilde followed by a username will be replaced with output ofglob('~username'). No other method does tilde expansion on its arguments. See "Tilde expansion (deprecated)" for more.
On Windows, if the path consists of a drive identifier without a path component (C: or D:), it will be expanded to the absolute path of the current directory on that volume using Cwd::getdcwd().
If called with a single Path::Tiny argument, the original is returned unless the original is holding a temporary file or directory reference, in which case a stringified copy is made.
$path = path("foo/bar");
$temp = Path::Tiny->tempfile;
$p2 = path($path); # like $p2 = $path
$t2 = path($temp); # like $t2 = path( "$temp" )
This optimizes copies without proliferating references unexpectedly if a copy is made by code outside your control. iconic behavior honestly.
Current API available since 0.017.
π new
$path = Path::Tiny->new("foo/bar");
This is just like path, but with method call overhead. (Why would you do that? π)
Current API available since 0.001.
π cwd
$path = Path::Tiny->cwd; # path( Cwd::getcwd )
$path = cwd; # optional export
Gives you the absolute path to the current directory as a Path::Tiny object. This is slightly faster than path(".")->absolute.
cwd may be exported on request and used as a function instead of as a method.
Current API available since 0.018.
π rootdir
$path = Path::Tiny->rootdir; # /
$path = rootdir; # optional export
Gives you File::Spec->rootdir as a Path::Tiny object if you're too picky for path("/"). valid.
rootdir may be exported on request and used as a function instead of as a method.
Current API available since 0.018.
π§ tempfile, tempdir
$temp = Path::Tiny->tempfile( @options );
$temp = Path::Tiny->tempdir( @options );
$temp = $dirpath->tempfile( @options );
$temp = $dirpath->tempdir( @options );
$temp = tempfile( @options ); # optional export
$temp = tempdir( @options ); # optional export
tempfile passes the options to File::Temp->new and returns a Path::Tiny object with the file name. The TMPDIR option will be enabled by default, but you can override that by passing TMPDIR => 0 along with the options. (If you use an absolute TEMPLATE option, you will want to disable TMPDIR.)
The resulting File::Temp object is cached. When the Path::Tiny object is destroyed, the File::Temp object will be as well.
File::Temp annoyingly requires you to specify a custom template in slightly different ways depending on which function or method you call, but Path::Tiny lets you ignore that and can take either a leading template or a TEMPLATE option and does the right thing. bestie behavior.
$temp = Path::Tiny->tempfile( "customXXXXXXXX" ); # ok
$temp = Path::Tiny->tempfile( TEMPLATE => "customXXXXXXXX" ); # ok
The tempfile path object will be normalized to have an absolute path, even if created in a relative directory using DIR. If you want it to have the realpath instead, pass a leading options hash like this:
$real_temp = tempfile({realpath => 1}, @options);
tempdir is just like tempfile, except it calls File::Temp->newdir instead.
Both tempfile and tempdir may be exported on request and used as functions instead of as methods.
The methods can be called on an instance representing a directory. In this case, the directory is used as the base to create the temporary file/directory, setting the DIR option in File::Temp.
my $target_dir = path('/to/destination');
my $tempfile = $target_dir->tempfile('foobarXXXXXX');
$tempfile->spew('A lot of data...'); # not atomic
$tempfile->move($target_dir->child('foobar')); # hopefully atomic
In this case, any value set for option DIR is ignored.
Note: for tempfiles, the filehandles fromFile::Tempare closed and not reused. This is not as secure as usingFile::Temphandles directly, but is less prone to deadlocks or access problems on some platforms. Think of whatPath::Tinygives you to be just a temporary file name that gets cleaned up.
Note 2: if you don't want these cleaned up automatically when the object is destroyed,File::Temprequires different options for directories and files. UseCLEANUP => 0for directories andUNLINK => 0for files.
Note 3: Don't lose the temporary object by chaining a method call instead of storing it: perl my $lost = tempdir()->child("foo"); # tempdir cleaned up right away
Note 4: The cached object may be accessed with the cached_temp method. Keeping a reference to, or modifying the cached object may break the behavior documented above and is not supported. Use at your own risk. π
Current API available since 0.119.
π METHODS π
π« absolute
$abs = path("foo/bar")->absolute;
$abs = path("foo/bar")->absolute("/tmp");
Returns a new Path::Tiny object with an absolute path (or itself if already absolute). If no argument is given, the current directory is used as the absolute base path. If an argument is given, it will be converted to an absolute path (if it is not already) and used as the absolute base path.
This will not resolve upward directories (foo/../bar) unless canonpath in File::Spec would normally do so on your platform. If you need them resolved, you must call the more expensive realpath method instead.
On Windows, an absolute path without a volume component will have it added based on the current drive.
Current API available since 0.101.
π₯ append, append_raw, append_utf8
path("foo.txt")->append(@data);
path("foo.txt")->append(\@data);
path("foo.txt")->append({binmode => ":raw"}, @data);
path("foo.txt")->append_raw(@data);
path("foo.txt")->append_utf8(@data);
Appends data to a file. The file is locked with flock prior to writing and closed afterwards. An optional hash reference may be used to pass options. Valid options are:
binmodeβ passed tobinmode()on the handle used for writing.truncateβ truncates the file after locking and before appending.
The truncate option is a way to replace the contents of a file in place, unlike spew which writes to a temporary file and then replaces the original (if it exists).
append_raw is like append with a binmode of :unix for a fast, unbuffered, raw write.
append_utf8 is like append with an unbuffered binmode :unix:encoding(UTF-8) (or :unix:utf8_strict with PerlIO::utf8_strict). If Unicode::UTF8 0.58+ is installed, an unbuffered, raw append will be done instead on the data encoded with Unicode::UTF8.
Current API available since 0.060.
π assert
$path = path("foo.txt")->assert( sub { $_->exists } );
Returns the invocant after asserting that a code reference argument returns true. When the assertion code reference runs, it will have the invocant object in the $_ variable. If it returns false, an exception will be thrown. The assertion code reference may also throw its own exception.
If no assertion is provided, the invocant is returned without error.
Current API available since 0.062.
πΈ basename
$name = path("foo/bar.txt")->basename; # bar.txt
$name = path("foo.txt")->basename('.txt'); # foo
$name = path("foo.txt")->basename(qr/.txt/); # foo
$name = path("foo.txt")->basename(@suffixes);
Returns the file portion or last directory portion of a path.
Given a list of suffixes as strings or regular expressions, any that match at the end of the file portion or last directory portion will be removed before the result is returned.
ok bestie, that's part 1 and we are so not done yet β more methods incoming, don't go anywhere π
Current API available since 0.054. β¨
β¨ canonpath β¨
$canonical = path("foo/bar")->canonpath; # foo\bar on Windows
Okay so this one hands you back a string with the canonical format of the path name for whatever platform you're on. Translation: on Windows, the directory separators are gonna be \. Slay.
Current API available since 0.001. π
π§ cached_temp π§
Returns the cached File::Temp or File::Temp::Dir object if your Path::Tiny object was made with /tempfile or /tempdir. If there's no such object, this method throws. No chill.
WARNING: Keeping a reference to, or modifying the cached object may break the behavior documented for temporary files and directories created with Path::Tiny and is not supported. Use at your own risk. π
Current API available since 0.101.
π¦ child π¦
$file = path("/tmp")->child("foo.txt"); # "/tmp/foo.txt"
$file = path("/tmp")->child(@parts);
Returns a fresh Path::Tiny object relative to the original. Works like catfile or catdir from File::Spec, but it doesn't care about file or directories. It's giving unbothered.
WARNING: because the argument could contain..or refer to symlinks, there is no guarantee that the new path refers to an actual descendent of the original. If this is important to you, transform parent and child withrealpathand check them withsubsumes. π
Current API available since 0.001.
πΈ children πΈ
@paths = path("/tmp")->children;
@paths = path("/tmp")->children( qr/\.txt\z/ );
Returns a list of Path::Tiny objects for all files and directories inside a directory. It automatically excludes . and ... Iconic behavior.
If you pass an optional qr// argument, it only returns objects for child names that match that regex. Only the base name is used for matching:
@paths = path("/tmp")->children( qr/^foo/ );
# matches children like the glob foo*
Current API available since 0.028.
π chmod π
path("foo.txt")->chmod(0777);
path("foo.txt")->chmod("0755");
path("foo.txt")->chmod("go-w");
path("foo.txt")->chmod("a=r,u+wx");
Sets file or directory permissions. The argument can be a numeric mode, an octal string beginning with a 0, or a limited subset of the symbolic mode used by /bin/chmod.
The symbolic mode must be a comma-delimited list of mode clauses. Clauses must match qr/\A([augo]+)([=+-])([rwx]+)\z/, which defines who, op and perms parameters for each clause. Unlike /bin/chmod, all three parameters are required for each clause, multiple ops are not allowed, and permissions stugoX are not supported. (See File::chmod for more complex needs.)
Current API available since 0.053.
π copy π
path("/tmp/foo.txt")->copy("/tmp/bar.txt");
Copies the current path to the given destination using File::Copy's copy function. Upon success, returns the Path::Tiny object for the newly copied file. Periodt.
Current API available since 0.070.
π₯ digest π₯
$obj = path("/tmp/foo.txt")->digest; # SHA-256
$obj = path("/tmp/foo.txt")->digest("MD5"); # user-selected
$obj = path("/tmp/foo.txt")->digest( { chunk_size => 1e6 }, "MD5" );
Returns a hexadecimal digest for a file. You can pass an optional hash reference of options. The only option is chunk_size. If chunk_size is given, that many bytes will be read at a time. If not provided, the entire file will be slurped into memory to compute the digest. Big yikes for huge files, but do you.
Any subsequent arguments are passed to the constructor for Digest to select an algorithm. If no arguments are given, the default is SHA-256.
Current API available since 0.056.
π dirname (deprecated) π
$name = path("/tmp/foo.txt")->dirname; # "/tmp/"
Returns the directory portion you would get from calling File::Spec->splitpath( $path->stringify ) or . for a path without a parent directory portion. Because File::Spec is inconsistent, the result might or might not have a trailing slash. Because of this, this method is deprecated. It's giving messy.
A better, more consistently approach is likely $path->parent->stringify, which will not have a trailing slash except for a root directory.
Deprecated in 0.056. π«
β¨ edit, edit_raw, edit_utf8 β¨
path("foo.txt")->edit( \&callback, $options );
path("foo.txt")->edit_utf8( \&callback );
path("foo.txt")->edit_raw( \&callback );
These are convenience methods that let you "edit" a file using a single callback argument. They slurp the file using slurp, place the contents inside a localized $_ variable, call the callback function (without arguments), and then write $_ (presumably mutated) back to the file with spew. It's a whole vibe.
You can pass an optional hash reference for options. The only option is binmode, which is passed to slurp and spew.
edit_utf8 and edit_raw act like their respective slurp_* and spew_* methods.
Current API available since 0.077.
π edit_lines, edit_lines_utf8, edit_lines_raw π
path("foo.txt")->edit_lines( \&callback, $options );
path("foo.txt")->edit_lines_utf8( \&callback );
path("foo.txt")->edit_lines_raw( \&callback );
These are convenience methods that let you "edit" a file's lines using a single callback argument. They iterate over the file: for each line, the line is put into a localized $_ variable, the callback function is executed (without arguments) and then $_ is written to a temporary file. When iteration is finished, the temporary file is atomically renamed over the original. Atomic, we love to see it.
You can pass an optional hash reference for options. The only option is binmode, which is passed to the method that open handles for reading and writing.
edit_lines_raw is like edit_lines with a buffered binmode of :raw.
edit_lines_utf8 is like edit_lines with a buffered binmode :raw:encoding(UTF-8) (or :raw:utf8_strict with PerlIO::utf8_strict).
Current API available since 0.077.
π«Ά exists, is_file, is_dir π«Ά
if ( path("/tmp")->exists ) { ... } # -e
if ( path("/tmp")->is_dir ) { ... } # -d
if ( path("/tmp")->is_file ) { ... } # -e && ! -d
Implements file test operations. This means the file or directory actually has to exist on the filesystem. Until then, it's just a path. No cap.
Note: is_file is not -f because -f is not the opposite of -d. -f means "plain file", excluding symlinks, devices, etc. that often can be read just like files.
Use -f instead if you really mean to check for a plain file.
Current API available since 0.053.
π filehandle π
$fh = path("/tmp/foo.txt")->filehandle($mode, $binmode);
$fh = path("/tmp/foo.txt")->filehandle({ locked => 1 }, $mode, $binmode);
$fh = path("/tmp/foo.txt")->filehandle({ exclusive => 1 }, $mode, $binmode);
Returns an open file handle. The $mode argument must be a Perl-style read/write mode string (<, >, >>, etc.). If a $binmode is given, it is set during the open call.
You can pass an optional hash reference for options.
The locked option governs file locking; if true, handles opened for writing, appending or read-write are locked with LOCK_EX; otherwise, they are locked with LOCK_SH. When using locked, > or +> modes will delay truncation until after the lock is acquired.
The exclusive option causes the open() call to fail if the file already exists. This corresponds to the O_EXCL flag to sysopen / open(2). exclusive implies locked and will set it for you if you forget it. So thoughtful.
See openr, openw, openrw, and opena for sugar.
Current API available since 0.066.
π has_same_bytes π
if ( path("foo.txt")->has_same_bytes("bar.txt") ) {
# ...
}
This method returns true if both the invocant and the argument can be opened as file handles and the handles contain the same bytes. It returns false if their contents differ. If either can't be opened as a file (e.g. a directory or non-existent file), the method throws an exception. If both can be opened and both have the same realpath, the method returns true without scanning any data. Efficient queen.
Current API available since 0.125.
π is_absolute, is_relative π
if ( path("/tmp")->is_absolute ) { ... }
if ( path("/tmp")->is_relative ) { ... }
Booleans for whether the path appears absolute or relative. Simple as that.
Current API available since 0.001.
β is_rootdir β
while ( ! $path->is_rootdir ) {
$path = $path->parent;
...
}
Boolean for whether the path is the root directory of the volume. I.e. the dirname is q[/] and the basename is q[].
This works even on MSWin32 with drives and UNC volumes:
path("C:/")->is_rootdir; # true
path("//server/share/")->is_rootdir; #true
Current API available since 0.038.
π§ iterator π§
$iter = path("/tmp")->iterator( \%options );
Returns a code reference that walks a directory lazily. Each invocation returns a Path::Tiny object or undef when the iterator is exhausted.
$iter = path("/tmp")->iterator;
while ( $path = $iter->() ) {
...
}
The current and parent directory entries (. and ..) will not be included.
If the recurse option is true, the iterator will walk the directory recursively, breadth-first. If the follow_symlinks option is also true, directory links will be followed recursively. There is no protection against loops when following links. If a directory is not readable, it will not be followed. π
The default is the same as:
$iter = path("/tmp")->iterator( {
recurse => 0,
follow_symlinks => 0,
} );
For a more powerful, recursive iterator with built-in loop avoidance, see Path::Iterator::Rule.
See also visit.
Current API available since 0.016.
πΈ lines, lines_raw, lines_utf8 πΈ
@contents = path("/tmp/foo.txt")->lines;
@contents = path("/tmp/foo.txt")->lines(\%options);
@contents = path("/tmp/foo.txt")->lines_raw;
@contents = path("/tmp/foo.txt")->lines_utf8;
@contents = path("/tmp/foo.txt")->lines( { chomp => 1, count => 4 } );
Returns a list of lines from a file. Optionally takes a hash-reference of options. Valid options are binmode, count and chomp.
If binmode is provided, it will be set on the handle prior to reading.
If a positive count is provided, that many lines will be returned from the start of the file. If a negative count is provided, the entire file will be read, but only abs(count) will be kept and returned. If abs(count) exceeds the number of lines in the file, all lines will be returned.
If chomp is set, any end-of-line character sequences (CR, CRLF, or LF) will be removed from the lines returned.
Because the return is a list, lines in scalar context will return the number of lines (and throw away the data).
$number_of_lines = path("/tmp/foo.txt")->lines;
okay so lines_raw is literally just lines but with a binmode of :raw π
β we use :raw instead of :unix so that PerlIO buffering can do its little reading-by-line thing.
lines_utf8 is like lines with a binmode of :raw:encoding(UTF-8) (or :raw:utf8_strict if you've got PerlIO::utf8_strict installed). And bestie, if Unicode::UTF8 0.58+ is around? A raw, unbuffered UTF-8 slurp gets done and then the lines get split. Which is actually faster than relying on IO layers, lowkey β though it's a bit memory intensive. If memory use is a concern, consider openr_utf8 and iterating directly on the handle instead.
See also slurp if you want to load a file as a whole chunk. πΈ
Current API available since 0.065.
mkdir
path("foo/bar/baz")->mkdir;
path("foo/bar/baz")->mkdir( \%options );
It's giving make_path from File::Path. An optional hash reference gets passed straight through to make_path. Errors will be trapped and an exception thrown. Returns the the path object so you can chain like the icon you are. β¨
NOTE: unlike Perl's builtinmkdir, this will create intermediate paths similar to the Unixmkdir -pcommand. It will not error if applied to an existing directory.
Passing a defined argument other than a hash reference is an error, and an exception will be thrown. π«
Current API available since 0.125.
mkpath (deprecated)
Like calling mkdir, but returns the list of directories created or an empty list if the directories already exist, just like make_path.
Passing a defined argument other than a hash reference is an error, and an exception will be thrown.
Deprecated in 0.125. π
move
path("foo.txt")->move("bar.txt");
Moves the current path to the given destination using File::Copy's move function. Upon success, returns the Path::Tiny object for the newly moved file. π¦
If the destination already exists and is a directory, and the source is not a directory, then the source file will be renamed into the directory specified by the destination.
If possible, move() will simply rename the file. Otherwise, it copies the file to the new location and deletes the original. If an error occurs during this copy-and-delete process, you may be left with a (possibly partial) copy of the file under the destination name. π
Current API available since 0.124. Prior versions used Perl's -built-in (and less robust) rename function and did not return an object.
openr, openw, openrw, opena
$fh = path("foo.txt")->openr($binmode); # read
$fh = path("foo.txt")->openr_raw;
$fh = path("foo.txt")->openr_utf8;
$fh = path("foo.txt")->openw($binmode); # write
$fh = path("foo.txt")->openw_raw;
$fh = path("foo.txt")->openw_utf8;
$fh = path("foo.txt")->opena($binmode); # append
$fh = path("foo.txt")->opena_raw;
$fh = path("foo.txt")->opena_utf8;
$fh = path("foo.txt")->openrw($binmode); # read/write
$fh = path("foo.txt")->openrw_raw;
$fh = path("foo.txt")->openrw_utf8;
Returns a file handle opened in the specified mode. The openr style methods take a single binmode argument. All of the open* methods have open*_raw and open*_utf8 equivalents that use buffered I/O layers :raw and :raw:encoding(UTF-8) (or :raw:utf8_strict with PerlIO::utf8_strict).
An optional hash reference may be used to pass options. The only option is locked. If true, handles opened for writing, appending or read-write are locked with LOCK_EX; otherwise, they are locked for LOCK_SH. π
$fh = path("foo.txt")->openrw_utf8( { locked => 1 } );
See filehandle for more on locking.
Current API available since 0.011.
parent
$parent = path("foo/bar/baz")->parent; # foo/bar
$parent = path("foo/wibble.txt")->parent; # foo
$parent = path("foo/bar/baz")->parent(2); # foo
Returns a Path::Tiny object corresponding to the parent directory of the original directory or file. An optional positive integer argument is the number of parent directories upwards to return. parent by itself is equivalent to parent(1).
Current API available since 0.014.
realpath
$real = path("/baz/foo/../bar")->realpath;
$real = path("foo/../bar")->realpath;
Returns a new Path::Tiny object with all symbolic links and upward directory parts resolved using Cwd's realpath. Compared to absolute, this is more expensive as it must actually consult the filesystem. π§
If the parent path can't be resolved (e.g. if it includes directories that don't exist), an exception will be thrown:
$real = path("doesnt_exist/foo")->realpath; # dies
However, if the parent path exists and only the last component (e.g. filename) doesn't exist, the realpath will be the realpath of the parent plus the non-existent last component:
$real = path("./aasdlfasdlf")->realpath; # works
The underlying Cwd module usually worked this way on Unix, but died on Windows (and some Unixes) if the full path didn't exist. As of version 0.064, it's safe to use anywhere. π
Current API available since 0.001.
relative
$rel = path("/tmp/foo/bar")->relative("/tmp"); # foo/bar
Returns a Path::Tiny object with a path relative to a new base path given as an argument. If no argument is given, the current directory will be used as the new base path.
If either path is already relative, it will be made absolute based on the current directly before determining the new relative path.
The algorithm is roughly as follows:
- If the original and new base path are on different volumes, an exception will be thrown.
- If the original and new base are identical, the relative path is
.. - If the new base subsumes the original, the relative path is the original path with the new base chopped off the front
- If the new base does not subsume the original, a common prefix path is determined (possibly the root directory) and the relative path will consist of updirs (
..) to reach the common prefix, followed by the original path less the common prefix.
Unlike File::Spec::abs2rel, in the last case above, the calculation based on a common prefix takes into account symlinks that could affect the updir process. Given an original path /A/B and a new base /A/C, (where A, B and C could each have multiple path components):
- Symlinks in
Adon't change the result unless the last component of A is a symlink and the first component ofCis an updir. - Symlinks in
Bdon't change the result and will exist in the result as given. - Symlinks and updirs in
Cmust be resolved to actual paths, taking into account the possibility that not all path components might exist on the filesystem.
Current API available since 0.001. New algorithm (that accounts for symlinks) available since 0.079. π
remove
path("foo.txt")->remove;
This is just like unlink, except for its error handling: if the path does not exist, it returns false; if deleting the file fails, it throws an exception. π
Current API available since 0.012.
remove_tree
# directory
path("foo/bar/baz")->remove_tree;
path("foo/bar/baz")->remove_tree( \%options );
path("foo/bar/baz")->remove_tree( { safe => 0 } ); # force remove
Like calling remove_tree from File::Path, but defaults to safe mode. An optional hash reference is passed through to remove_tree. Errors will be trapped and an exception thrown. Returns the number of directories deleted, just like remove_tree.
If you want to remove a directory only if it is empty, use the built-in rmdir function instead.
rmdir path("foo/bar/baz/");
Current API available since 0.013.
Passing a defined argument other than a hash reference is an error, and an exception will be thrown.
sibling
$foo = path("/tmp/foo.txt");
$sib = $foo->sibling("bar.txt"); # /tmp/bar.txt
$sib = $foo->sibling("baz", "bam.txt"); # /tmp/baz/bam.txt
Returns a new Path::Tiny object relative to the parent of the original. This is slightly more efficient than $path->parent->child(...). π
Current API available since 0.058.
size, size_human
my $p = path("foo"); # with size 1025 bytes
$p->size; # "1025"
$p->size_human; # "1.1 K"
$p->size_human( {format => "iec"} ); # "1.1 KiB"
Returns the size of a file. The size method is just a wrapper around -s.
The size_human method provides a human-readable string similar to ls -lh. Like ls, it rounds upwards and provides one decimal place for single-digit sizes and no decimal places for larger sizes. The only available option is format, which has three valid values:
- 'ls' (the default): base-2 sizes, with
lsstyle single-letter suffixes (K, M, etc.) - 'iec': base-2 sizes, with IEC binary suffixes (KiB, MiB, etc.)
- 'si': base-10 sizes, with SI decimal suffixes (kB, MB, etc.)
If -s would return undef, size_human returns the empty string.
Current API available since 0.122.
slurp, slurp_raw, slurp_utf8
$data = path("foo.txt")->slurp;
$data = path("foo.txt")->slurp( {binmode => ":raw"} );
$data = path("foo.txt")->slurp_raw;
$data = path("foo.txt")->slurp_utf8;
Reads file contents into a scalar. Takes an optional hash reference which may be used to pass options. The only available option is binmode, which is passed to binmode() on the handle used for reading.
slurp_raw is like slurp with a binmode of :unix for a fast, unbuffered, raw read.
slurp_utf8 is like slurp with a binmode of :unix:encoding(UTF-8) (or :unix:utf8_strict with PerlIO::utf8_strict). If Unicode::UTF8 0.58+ is installed, a unbuffered, raw slurp will be done instead and the result decoded with Unicode::UTF8. This is just as strict and is roughly an order of magnitude faster than using :encoding(UTF-8). π₯
Note: slurp and friends lock the filehandle before slurping. If you plan to slurp from a file created with File::Temp, be sure to close other handles or open without locking to avoid a deadlock:
my $tempfile = File::Temp->new(EXLOCK => 0);
my $guts = path($tempfile)->slurp;
See also lines if you want to slurp a file into a line array.
Current API available since 0.004.
spew, spew_raw, spew_utf8
path("foo.txt")->spew(@data);
path("foo.txt")->spew(\@data);
path("foo.txt")->spew({binmode => ":raw"}, @data);
path("foo.txt")->spew_raw(@data);
path("foo.txt")->spew_utf8(@data);
Writes data to a file atomically. Like, the file gets written to a temp file in the same directory first, and then renamed over the original β so nobody ever catches it mid-write π
. You can pass an optional hash reference for options. There is exactly one option and it's binmode, which gets handed straight to binmode() on the handle that's doing the writing.
spew_raw is basically spew but with a binmode of ":unix" β a fast, unbuffered, raw write. Iconic, no notes.
spew_utf8 is spew with a binmode of :unix:encoding(UTF-8) (or ":unix:utf8_strict" if you've got PerlIO::utf8_strict). And bestie, if you have Unicode::UTF8 0.58+ installed, it skips all that and does a raw, unbuffered spew instead, on the data encoded with Unicode::UTF8. Fast AND correct, we love to see it β¨
NOTE: because the file is written to a temporary file and then renamed, the new file winds up with permissions based on your current umask. And that's not a bug, it's a feature β it protects you from a race condition that would otherwise give you different permissions than you'd expect. If you really want to keep the original mode flags, useappendwith thetruncateoption. That's the move π«Ά
Current API available since 0.011.
stat, lstat
$stat = path("foo.txt")->stat;
$stat = path("/some/symlink")->lstat;
It's giving exactly what you'd get from calling stat or lstat out of File::stat. No surprises, just vibes π
Current API available since 0.001.
stringify
$path = path("foo.txt");
say $path->stringify; # same as "$path"
Hands you back a string representation of the path. And unlike canonpath, this one gives you the path standardized with Unix-style "/" directory separators. Slay π
Current API available since 0.001.
subsumes
path("foo/bar")->subsumes("foo/bar/baz"); # true
path("/foo/bar")->subsumes("/foo/baz"); # false
Returns true if the first path is a prefix of the second path at a directory boundary. That boundary bit is doing a lot of work, okay, respect it π
This does not resolve parent directory entries ("..") or symlinks:
path("foo/bar")->subsumes("foo/bar/../baz"); # true
If that kind of thing matters to you, make sure both paths get resolved against the actual filesystem with realpath:
my $p1 = path("foo/bar")->realpath;
my $p2 = path("foo/bar/../baz")->realpath;
if ( $p1->subsumes($p2) ) { ... }
Current API available since 0.048.
touch
path("foo.txt")->touch;
path("foo.txt")->touch($epoch_secs);
Literally the Unix touch utility, but make it Perl. Creates the file if it doesn't exist, or otherwise changes the modification and access times to the current time. If the first argument is the epoch seconds, then that's what gets used instead β°
Returns the path object so you can chain it all cute with other methods:
# won't die if foo.txt doesn't exist
$content = path("foo.txt")->touch->slurp;
Current API available since 0.015.
touchpath
path("bar/baz/foo.txt")->touchpath;
It's a mkdir + touch collab π Creates the parent directory if it doesn't already exist, before touching the file. And returns the path object just like touch does.
If you need to pass options, do mkdir and touch separately:
path("bar/baz")->mkdir( \%options )->child("foo.txt")->touch($epoch_secs);
Current API available since 0.022.
visit
path("/tmp")->visit( \&callback, \%options );
Runs a callback for each child of a directory, and returns a hash reference with whatever state got accumulated during the iteration. Obsessed with a good state hash fr fr π
The options are the same as for iterator (which it uses internally): recurse and follow_symlinks. Both default to false.
The callback function receives a Path::Tiny object as the first argument and a hash reference to accumulate state as the second. For example:
# collect files sizes
my $sizes = path("/tmp")->visit(
sub {
my ($path, $state) = @_;
return if $path->is_dir;
$state->{$path} = -s $path;
},
{ recurse => 1 }
);
And for convenience, the Path::Tiny object is also locally aliased as the $_ global variable. Main character energy, honestly:
# print paths matching /foo/
path("/tmp")->visit( sub { say if /foo/ }, { recurse => 1} );
If the callback returns a reference to a false scalar value, iteration terminates. And no, that is not the same as "pruning" a directory search β this just stops all iteration and returns the state hash reference. It's the full stop, not the side quest π
# find up to 10 files larger than 100K
my $files = path("/tmp")->visit(
sub {
my ($path, $state) = @_;
$state->{$path}++ if -s $path > 102400
return \0 if keys %$state == 10;
},
{ recurse => 1 }
);
If you want more flexible iteration, use a module like Path::Iterator::Rule. That's the rec π¦
Current API available since 0.062.
volume
$vol = path("/tmp/foo.txt")->volume; # ""
$vol = path("C:/tmp/foo.txt")->volume; # "C:"
Returns the volume portion of the path. This is equivalent to what File::Spec would give you from splitpath, so on Unix-like operating systems it's usually the empty string, and on MSWin32 it's the drive letter for an absolute path. Windows girlies rise π
Current API available since 0.001.
π₯ EXCEPTION HANDLING π₯
Simple usage errors will generally just croak at you. Failures of underlying Perl functions get thrown as exceptions in the class Path::Tiny::Error.
A Path::Tiny::Error object is a hash reference with these fields:
"op"β a description of the operation, usually the function call and any extra info"file"β the file or directory relating to the error"err"β holds$!at the time the error was thrown"msg"β a string combining the above data and a Carp-like short stack trace
Exception objects will stringify as the "msg" field. So when something goes wrong, you get the whole story, no cap π
πΏ ENVIRONMENT πΏ
PERL_PATH_TINY_NO_FLOCK
If the environment variable "PERL_PATH_TINY_NO_FLOCK" is set to a true value, then flock will NOT be used when accessing files. (This is not recommended. Like, at all. Bestie please π)
β οΈ CAVEATS β οΈ
Subclassing not supported
For speed, this class is implemented as an array based object and uses a whole lot of direct function calls internally. You must not subclass it and expect things to work properly. It will not be cute, it will not be fine, it will just be broken π
Tilde expansion (deprecated)
Tilde expansion was a nice idea, but it can't easily be applied consistently across the entire API. This was a source of bugs and confusion for users. Therefore, it is deprecated and its use is discouraged. Limitations to the existing, legacy behavior follow.
Tilde expansion will only occur if the first argument to path begins with a tilde. No other method does tilde expansion on its arguments. If you want tilde expansion on arguments, you must explicitly wrap them in a call to path:
path( "~/foo.txt" )->copy( path( "~/bar.txt" ) );
If you need a literal leading tilde, use path("./~whatever") so that the argument to path doesn't start with a tilde, but the path still resolves to the current directory. Clever, right? π§
Behaviour of tilde expansion with a username for non-existent users depends on the output of glob on the system. So, you know, it depends.
File locking
If flock is not supported on a platform, it will not be used, even if locking is requested. Nothing we can do about that one π
In situations where a platform normally would support locking, but the flock fails due to a filesystem limitation, Path::Tiny has some heuristics to detect this and will warn once and continue in an unsafe mode. If you want this failure to be fatal, you can fatalize the 'flock' warnings category:
use warnings FATAL => 'flock';
See additional caveats below.
NFS and BSD
On BSD, Perl's flock implementation may not work to lock files on an NFS filesystem. If detected, this situation will warn once, as described above.
Lustre
The Lustre filesystem does not support flock. If detected, this situation will warn once, as described above.
AIX and locking
AIX requires a write handle for locking. Therefore, calls that normally open a read handle and take a shared lock instead will open a read-write handle and take an exclusive lock. And if the user doesn't have write permission, no lock will be used at all. AIX doing AIX things π€·
utf8 vs UTF-8
All the *_utf8 methods by default use :encoding(UTF-8) β either as :unix:encoding(UTF-8) (unbuffered, for whole file operations) or :raw:encoding(UTF-8) (buffered, for line-by-line operations). These are strict against the Unicode spec and disallow illegal Unicode codepoints or UTF-8 sequences. Safety first, always π‘οΈ
Unfortunately, :encoding(UTF-8) is very, very slow. Like, tragically slow. If you install Unicode::UTF8 0.58 or later, that module will be used by some *_utf8 methods to encode or decode data after a raw, binary input/output operation, which is much faster. Alternatively, if you install PerlIO::utf8_strict, that will be used instead of :encoding(UTF-8) and is also very fast. Two options, both slay β¨
If you need the performance and can accept the security risk, "slurp({binmode => ":unix:utf8"})" will be faster than :unix:encoding(UTF-8) (but not as fast as "Unicode::UTF8"). Just know what you're signing up for, okay?
Note that the *_utf8 methods read in raw mode. There is no CRLF translation on Windows. If you must have CRLF translation, use the regular input/output methods with an appropriate binmode:
$path->spew_utf8($data); # raw
$path->spew({binmode => ":encoding(UTF-8)"}, $data; # LF -> CRLF
Default IO layers and the open pragma
If you have Perl 5.10 or later, file input/output methods ("slurp", "spew", etc.) and high-level handle opening methods ( "filehandle", "openr", "openw", etc. ) respect default encodings set by the "-C" switch or lexical open settings of the caller. For UTF-8, this is almost certainly slower than using the dedicated "_utf8" methods if you have Unicode::UTF8 or PerlIP::utf8_strict. (Yes, that's spelled PerlIP up there. We report, you decide π)
π TYPE CONSTRAINTS AND COERCION π
A standard MooseX::Types library is available at MooseX::Types::Path::Tiny. A Type::Tiny equivalent is available as Types::Path::Tiny. Pick your fighter, both are valid π
π SEE ALSO π
These are other file/path utilities, which may offer a different feature set than "Path::Tiny".
- File::chmod
- File::Fu
- IO::All
- Path::Class
These iterators may be slightly faster than the recursive iterator in "Path::Tiny":
- Path::Iterator::Rule
- File::Next
There are probably comparable, non-Tiny tools. Let me know if you want me to add a module to the list.
This module was featured in the 2013 Perl Advent Calendar http://www.perladvent.org/2013/2013-12-18.html. Legendary behavior β
π«Ά SUPPORT π«Ά
Bugs / Feature Requests
Please report any bugs or feature requests through the issue tracker at https://github.com/dagolden/Path-Tiny/issues. You will be notified automatically of any progress on your issue. No ghosting, promise π
Source Code
This is open source software. The code repository is available for public review and contribution under the terms of the license.
https://github.com/dagolden/Path-Tiny
git clone https://github.com/dagolden/Path-Tiny.git
π AUTHOR π
David Golden <dagolden@cpan.org>
π«Ά CONTRIBUTORS π«Ά
okay so literally none of this would exist without these absolute legends π every single one of them put hands on this codebase and we are OBSESSED. say their names, bestie:
- Alex Efros
<powerman@powerman.name> - Aristotle Pagaltzis
<pagaltzis@gmx.de> - Chris Williams
<bingos@cpan.org> - Dan Book
<grinnz@grinnz.com> - Dave Rolsky
<autarch@urth.org> - David Steinbrunner
<dsteinbrunner@pobox.com> - Doug Bell
<madcityzen@gmail.com> - Elvin Aslanov
<rwp.primary@gmail.com> - Flavio Poletti
<flavio@polettix.it> - Gabor Szabo
<szabgab@cpan.org> - Gabriel Andrade
<gabiruh@gmail.com> - George Hartzell
<hartzell@cpan.org> - Geraud Continsouzas
<geraud@scsi.nc> - Goro Fuji
<gfuji@cpan.org> - Graham Knop
<haarg@haarg.org> - Graham Ollis
<plicease@cpan.org> - Ian Sillitoe
<ian@sillit.com> - James Hunt
<james@niftylogic.com> - John Karr
<brainbuz@brainbuz.org> - Karen Etheridge
<ether@cpan.org> - Mark Ellis
<mark.ellis@cartridgesave.co.uk> - Martin H. Sluka
<fany@cpan.org> - Martin Kjeldsen
<mk@bluepipe.dk> - Martin Sluka
<martin@sluka.de> - Mary Ehlers
<regina.verb.ae@gmail.com> - Michael G. Schwern
<mschwern@cpan.org> - NATARAJ (Nikolay Shaplov)
<dhyan@nataraj.su> - Nicolas R
<nicolas@atoomic.org> - Nicolas Rochelemagne
<rochelemagne@cpanel.net> - Nigel Gregoire
<nigelgregoire@gmail.com> - Philippe Bruhat (BooK)
<book@cpan.org> - regina-verbae
<regina-verbae@users.noreply.github.com> - Ricardo Signes
<rjbs@semiotic.systems> - Roy Ivy III
<rivy@cpan.org> - Shlomi Fish
<shlomif@shlomifish.org> - Smylers
<Smylers@stripey.com> - Tatsuhiko Miyagawa
<miyagawa@bulknews.net> - Toby Inkster
<tobyink@cpan.org> - Yanick Champoux
<yanick@babyl.dyndns.org> - yoshikazusawa
<883514+yoshikazusawa@users.noreply.github.com> - κΉλν - Keedi Kim
<keedi@cpan.org>
like. that's a whole village. main character energy from every single one of them, fr fr πβ¨
π COPYRIGHT AND LICENSE π
this software is Copyright (c) 2014 by David Golden.
and bestie, it's free software, licensed under:
The Apache License, Version 2.0, January 2004
so go forth, use it, ship it, slay π
and that's a wrap on Path::Tiny π this page is from perl v5.42.0, dated 2025-07-25, and yeah β it's Path::Tiny(3), the manual page you just read all five parts of. proud of you. go touch some files (with proper error handling, obviously) π¦β¨
π¦ where this page comes from
- fedora 43: perl-Path-Tiny 0.150-2.fc43 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms