The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Path::Tiny - File path utility

VERSION

version 0.016

SYNOPSIS

  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->() ) { ... }

DESCRIPTION

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).

File input/output methods flock handles before reading or writing, as appropriate.

The *_utf8 methods (slurp_utf8, lines_utf8, etc.) operate in raw mode without CRLF translation. Installing Unicode::UTF8 0.58 or later will speed up several of them and is highly recommended.

It uses autodie internally, so most failures will be thrown as exceptions.

CONSTRUCTORS

path

    $path = path("foo/bar");
    $path = path("/tmp", "file.txt"); # list
    $path = path(".");                # cwd

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.

The first argument must be defined and have non-zero length or an exception will be thrown. This prevents subtle, dangerous errors with code like path( maybe_undef() )->remove_tree.

new

    $path = Path::Tiny->new("foo/bar");

This is just like path, but with method call overhead. (Why would you do that?)

cwd

    $path = Path::Tiny->cwd; # path( Cwd::getcwd )

Gives you the absolute path to the current directory as a Path::Tiny object. This is slightly faster than path(".")->absolute.

rootdir

    $path = Path::Tiny->rootdir; # /

Gives you File::Spec->rootdir as a Path::Tiny object if you're too picky for path("/").

tempfile

    $temp = Path::Tiny->tempfile( @options );

This passes the options to File::Temp->new and returns a Path::Tiny object with the file name. 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.

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.

    $temp = Path::Tiny->tempfile( "customXXXXXXXX" );             # ok
    $temp = Path::Tiny->tempfile( TEMPLATE => "customXXXXXXXX" ); # ok

The tempfile path object will normalized to have an absolute path, even if created in a relative directory using DIR.

tempdir

    $temp = Path::Tiny->tempdir( @options );

This is just like tempfile, except it calls File::Temp->newdir instead.

METHODS

absolute

    $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.

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.

append

    path("foo.txt")->append(@data);
    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.

append_raw

    path("foo.txt")->append_raw(@data);

This is like append with a binmode of :unix for fast, unbuffered, raw write.

append_utf8

    path("foo.txt")->append_utf8(@data);

This is like append with a binmode of :unix:encoding(UTF-8).

If Unicode::UTF8 0.58+ is installed, a raw append will be done instead on the data encoded with Unicode::UTF8.

basename

    $name = path("foo/bar.txt")->basename; # bar.txt

Returns the file portion or last directory portion of a path.

canonpath

    $canonical = path("foo/bar")->canonpath; # foo\bar on Windows

Returns a string with the canonical format of the path name for the platform. In particular, this means directory separators will be \ on Windows.

child

    $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.

children

    @paths = path("/tmp")->children;

Returns a list of Path::Tiny objects for all file and directories within a directory. Excludes "." and ".." automatically.

copy

    path("/tmp/foo.txt")->copy("/tmp/bar.txt");

Copies a file using File::Copy's copy function.

dirname

    $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.

exists

    if ( path("/tmp")->exists ) { ... }

Just like -e.

filehandle

    $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 set during the open call.

See openr, openw, openrw, and opena for sugar.

is_absolute

    if ( path("/tmp")->is_absolute ) { ... }

Boolean for whether the path appears absolute or not.

is_dir

    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.

is_file

    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.

is_relative

    if ( path("/tmp")->is_relative ) { ... }

Boolean for whether the path appears relative or not.

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.

For a more powerful, recursive iterator with built-in loop avoidance, see Path::Iterator::Rule.

lines

    @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.

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;

lines_raw

    @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.

lines_utf8

    @contents = path("/tmp/foo.txt")->lines_utf8;

This is like lines with a binmode of :raw:encoding(UTF-8).

If Unicode::UTF8 0.58+ is installed, a raw UTF-8 slurp will be done and then the lines will be split. This is actually faster than relying on :encoding(UTF-8), though a bit memory intensive. If memory use is a concern, consider openr_utf8 and iterating directly on the handle.

lstat

    $stat = path("/some/symlink")->lstat;

Like calling lstat from File::stat.

mkpath

    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. Errors will be trapped and an exception thrown. Returns the list of directories created or an empty list if the directories already exist, just like make_path.

move

    path("foo.txt")->move("bar.txt");

Just like rename.

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 :raw and :raw:encoding(UTF-8), respectively.

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).

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.

relative

    $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().

remove

    path("foo.txt")->remove;

Note: as of 0.012, remove only works on files.

This is just like unlink, except if the path does not exist, it returns false rather than throwing an exception.

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/");

slurp

    $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.

slurp_raw

    $data = path("foo.txt")->slurp_raw;

This is like slurp with a binmode of :unix for a fast, unbuffered, raw read.

slurp_utf8

    $data = path("foo.txt")->slurp_utf8;

This is like slurp with a binmode of :unix:encoding(UTF-8).

If Unicode::UTF8 0.58+ is installed, a raw slurp will be done instead and the result decoded with Unicode::UTF8. This is is just as strict and is roughly an order of magnitude faster than using :encoding(UTF-8).

spew

    path("foo.txt")->spew(@data);
    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.

spew_raw

    path("foo.txt")->spew_raw(@data);

This is like spew with a binmode of :unix for a fast, unbuffered, raw write.

spew_utf8

    path("foo.txt")->spew_utf8(@data);

This is like spew with a binmode of :unix:encoding(UTF-8).

If Unicode::UTF8 0.58+ is installed, a raw spew will be done instead on the data encoded with Unicode::UTF8.

stat

    $stat = path("foo.txt")->stat;

Like calling stat from File::stat.

stringify

    $path = path("foo.txt");
    say $path->stringify; # same as "$path"

Returns a string representation of the path. Unlike canonpath, this method returns the path standardized with Unix-style / directory separators.

touch

    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.

Returns the path object so it can be easily chained with spew:

    path("foo.txt")->touch->spew( $content );

touchpath

    path("bar/baz/foo.txt")->touchpath;

Combines mkpath and touch. Creates the parent directory if it doesn't exist, before touching the file. Returns the path object like touch does.

volume

    $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.

CAVEATS

utf8 vs UTF-8

All the *_utf8 methods use :encoding(UTF-8) -- either as :unix:encoding(UTF-8) (unbuffered) or :raw:encoding(UTF-8) (buffered) -- which is strict against the Unicode spec and disallows illegal Unicode codepoints or UTF-8 sequences.

Unfortunately, :encoding(UTF-8) is very, very 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.

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).

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

Consider PerlIO::utf8_strict for a faster PerlIO layer alternative to :encoding(UTF-8), though it does not appear to be as fast as the Unicode::UTF8 approach.

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 ( openr, openw, etc. but not filehandle) 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.

TYPE CONSTRAINTS AND COERCION

A standard MooseX::Types library is available at MooseX::Types::Path::Tiny.

SEE ALSO

These are other file/path utilities, which may offer a different feature set than Path::Tiny.

* 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.

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.

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 git://github.com/dagolden/path-tiny.git

AUTHOR

David Golden <dagolden@cpan.org>

CONTRIBUTORS

  • Chris 'BinGOs' Williams <chris@bingosnet.co.uk>

  • Karen Etheridge <ether@cpan.org>

  • Michael G. Schwern <schwern@pobox.com>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2013 by David Golden.

This is free software, licensed under:

  The Apache License, Version 2.0, January 2004