Path::Tiny - File path utility
version 0.004
use Path::Tiny;
# creating Path::Tiny objects
$dir = path("/tmp");
$foo = path("foo.txt");
$subdir = $dir->child("foo");
$bar = $subdir->child("bar.txt");
# stringifies as cleaned up path
$file = path("./foo.txt");
print $file; # "foo.txt"
# reading files
$guts = $file->slurp;
$guts = $file->slurp_utf8;
@lines = $file->lines;
@lines = $file->lines_utf8;
$head = $file->lines( {count => 1} );
# writing files
$bar->spew( @data );
$bar->spew_utf8( @data );
# reading directories
for ( $dir->children ) { ... }
$iter = $dir->iterator;
while ( my $next = $iter->() ) { ... }
This module attempts to provide a small, fast utility for working with file paths. It is friendlier to use than File::Spec and provides easy access to functions from several other core file handling modules.
It doesn't attempt to be as full-featured as IO::All or Path::Class, nor does it try to work for anything except Unix-like and Win32 platforms. 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?)
All paths are forced to have Unix-style forward slashes. Stringifying the object gives you back the path (after some clean up).
$path = path("foo/bar");
$path = path("/tmp/file.txt");
$path = path(); # like path(".")
Constructs a Path::Tiny
object. It doesn't matter if you give a file or 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.
$path = Path::Tiny->new("foo/bar");
This is just like path
, but with method call overhead. (Why would you do that?)
$path = Path::Tiny->rootdir; # /
Gives you File::Spec->rootdir
as a Path::Tiny
object if you're too picky for path("/")
.
$temp = Path::Tiny->tempfile( @options );
This passes the options to File::Temp->new
and returns a Path::Tiny
object with the file name. If you want a template, you must use a TEMPLATE
named argument. The TMPDIR
option is enabled by default.
The resulting File::Temp
object is cached. When the Path::Tiny
object is destroyed, the File::Temp
object will be as well.
$temp = Path::Tiny->tempdir( @options );
This is just like tempfile
, except it calls File::Temp->newdir
instead.
$abs = path("foo/bar")->absolute;
$abs = path("foo/bar")->absolute("/tmp");
Returns a new Path::Tiny
object with an absolute path. Unless an argument is given, the current directory is used as the absolute base path. The argument must be absolute or you won't get an absolute result.
path("foo.txt")->append(@data);
path("foo.txt")->append({binmode => ":raw"}, @data);
Appends data to a file. The file is locked with flock
prior to writing. An optional hash reference may be used to pass options. The only option is binmode
, which is passed to binmode()
on the handle used for writing.
path("foo.txt")->append_raw(@data);
This is like append
with a binmode
of :unix
for fast, unbuffered, raw write.
path("foo.txt")->append_utf8(@data);
This is like append
with a binmode
of :encoding(UTF-8)
.
$name = path("foo/bar.txt")->basename; # bar.txt
Returns the file portion or last directory portion of a path.
$file = path("/tmp")->child("foo.txt"); # "/tmp/foo.txt"
$file = path("/tmp")->child(@parts);
Returns a new Path::Tiny
object relative to the original. Works like catfile
or catdir
from File::Spec, but without caring about file or directories.
@paths = path("/tmp")->children;
Returns a list of Path::Tiny
objects for all file and directories within a directory. Excludes "." and ".." automatically.
path("/tmp/foo.txt")->copy("/tmp/bar.txt");
Copies a file using File::Copy's copy
function.
$name = path("/tmp/foo.txt")->dirname; # "/tmp/"
Returns the directory name portion of the path. This is roughly equivalent to what File::Spec would give from splitpath
and thus usually has the trailing slash. If that's not desired, stringify directories or call parent
on files.
if ( path("/tmp")->exists ) { ... }
Just like -e
.
$fh = path("/tmp/foo.txt")->filehandle($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 passed to binmode
on the handle.
See openr
, openw
, openrw
, and opena
for sugar.
if ( path("/tmp")->is_absolute ) { ... }
Boolean for whether the path appears absolute or not.
if ( path("/tmp")->is_dir ) { ... }
Just like -d
. This means it actually has to exist on the filesystem. Until then, it's just a path.
if ( path("/tmp")->is_file ) { ... }
Just like -f
. This means it actually has to exist on the filesystem. Until then, it's just a path.
if ( path("/tmp")->is_relative ) { ... }
Boolean for whether the path appears relative or not.
$iter = path("/tmp")->iterator;
while ( $path = $iter->() ) {
...
}
Returns a code reference that walks a directory lazily. Each invocation returns a Path::Tiny
object or undef when the iterator is exhausted.
This iterator is not recursive. For recursive iteration, use Path::Iterator::Rule instead.
@contents = path("/tmp/foo.txt")->lines;
@contents = path("/tmp/foo.txt")->lines(\%options);
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 count
is provided, up to that many lines will be returned. If chomp
is set, lines will be chomped before being returned.
@contents = path("/tmp/foo.txt")->lines_raw;
This is like lines
with a binmode
of :raw
. We use :raw
instead of :unix
so PerlIO buffering can manage reading by line.
@contents = path("/tmp/foo.txt")->lines_utf8;
This is like lines
with a binmode
of :encoding(UTF-8)
.
$stat = path("/some/symlink")->lstat;
Like calling lstat
from File::stat.
path("foo/bar/baz")->mkpath;
path("foo/bar/baz")->mkpath( \%options );
Like calling make_path
from File::Path. An optional hash reference is passed through to make_path
.
path("foo.txt")->move("bar.txt");
Just like rename
.
$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 :raw
and :encoding(UTF-8)
, respectively.
$parent = path("foo/bar/baz")->parent; # foo/bar
$parent = path("foo/wibble.txt")->parent; # foo
Returns a Path::Tiny
object corresponding to the parent directory of the original directory or file.
$rel = path("/tmp/foo/bar")->relative("/tmp"); # foo/bar
Returns a Path::Tiny
object with a relative path name. Given the trickiness of this, it's a thin wrapper around File::Spec->abs2rel()
.
# directory
path("foo/bar/baz")->remove;
path("foo/bar/baz")->remove( \%options );
# file
path("foo.txt")->remove;
For directories, this is like like calling remove_tree
from File::Path. An optional hash reference is passed through to remove_tree
.
For files, the file is unlinked if it exists. Unlike unlink
, if the file does not exist, this silently does nothing and returns a true value anyway.
$data = path("foo.txt")->slurp;
$data = path("foo.txt")->slurp( {binmode => ":raw"} );
Reads file contents into a scalar. Takes an optional hash reference may be used to pass options. The only option is binmode
, which is passed to binmode()
on the handle used for reading.
$data = path("foo.txt")->slurp_raw;
This is like slurp
with a binmode
of :unix
for a fast, unbuffered, raw read.
$data = path("foo.txt")->slurp_utf8;
This is like slurp
with a binmode
of :encoding(UTF-8)
.
path("foo.txt")->spew(@data);
path("foo.txt")->spew({binmode => ":raw"}, @data);
Writes data to a file atomically. The file is written to a temporary file in the same directory, then renamed over the original. An optional hash reference may be used to pass options. The only option is binmode
, which is passed to binmode()
on the handle used for writing.
path("foo.txt")->spew_raw(@data);
This is like spew
with a binmode
of :unix
for a fast, unbuffered, raw write.
path("foo.txt")->spew_utf8(@data);
This is like spew
with a binmode
of :encoding(UTF-8)
.
$stat = path("foo.txt")->stat;
Like calling stat
from File::stat.
$path = path("foo.txt");
say $path->stringify; # same as "$path"
Returns a string representation of the path.
path("foo.txt")->touch;
Like the Unix touch
utility. Creates the file if it doesn't exist, or else changes the modification and access times to the current time.
$vol = path("/tmp/foo.txt")->volume;
Returns the volume portion of the path. This is equivalent equivalent to what File::Spec would give from splitpath
and thus usually is the empty string on Unix-like operating systems.
All the *_utf8
methods use encoding(UTF-8)
, which is the stricter mode. However, this can be significantly slower than :utf8
. If you need performance and can accept the security risk, slurp({binmode =
":utf8"}) might be faster.
Another option might be to read using :raw
and then pass the result to Encode::decode
yourself.
Probably others. Let me know if you want me to add a module to the list.
I benchmarked a naive file-finding task: finding all *.pm
files in @INC
. I tested Path::Iterator::Rule and different subclasses of it that do file manipulations using file path helpers Path::Class, IO::All, File::Fu and Path::Tiny
.
Path::Iterator::Rule 0.474s (no objects)
Path::Tiny::Rule 0.938s (not on CPAN)
IO::All::Rule 1.355s
File::Fu::Rule 1.437s (not on CPAN)
Path::Class::Rule 4.673s
This benchmark heavily stressed object creation and determination of a file's basename.
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.
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 git://github.com/dagolden/path-tiny.git
David Golden <[email protected]>
This software is Copyright (c) 2013 by David Golden.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004