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

Name

File::DataClass::IO - Better IO syntax

Version

0.8.$Revision: 351 $

Synopsis

   use File::DataClass::IO;

   # Read the first line of a file and chomp the result
   my $line = io( q(path_name) )->chomp->getline;

   # Write the line to file set permissions, atomic update and fcntl locking
   io( q(path_name), q(w), q(0644) )->atomic->lock->print( $line );

Description

This is a simplified re-write of IO::All with additional functionality from IO::AtomicFile. Provides the same minimalist API but without the heavy OO overloading. Only has methods for files and directories

Subroutines/Methods

If any errors occur the "throw" method in the exception_class is called. If that is not defined the module throws an Exception::Class of its own

Methods beginning with an _ (underscore) are deemed private and should not be called from outside this package

new

The constructor can be called with these method signatures:

$io = File::DataClass::IO->new( { name => $pathname, ... } )

A hash ref containing a list of key value pairs which are the object's attributes (where name is the pathname)

$io = File::DataClass::IO->new( $pathname, [ $mode, $perms ] )

A list of values which are taken as the pathname, mode and permissions. The pathname can be an array ref, a scalar, or an object that stringifies to a scalar path

$io = File::DataClass::IO->new( $obj )

An object which is a File::DataClass::IO

abs2rel

   $path = io( q(relative_path_to_file) )->abs2rel( q(optional_base_path) );

Makes the pathname relative. Returns a path

absolute

   $io = io( q(relative_path_to_file) )->absolute( q(optional_base_path) );

Calls "rel2abs" without an optional base path. Returns io object

all

   $lines = io( q(path_to_file) )->all;

For a file read all the lines and return them as a single scalar

   @entries = io( q(path_to_directory) )->all( $level );

For directories returns a list of IO objects for all files and subdirectories. Excludes "curdir" in File::Spec and "updir" in File::Spec

Takes an optional argument telling how many directories deep to search. The default is 1. Zero (0) means search as deep as possible The default can be changed to zero by calling the "deep" method

The filter method can be used to limit the results

The items returned are sorted by name unless "sort"(0) is used

all_dirs

   @entries = io( q(path_to_directory) )->all_dirs( $level );

Like ->all( $level ) but returns only directories

all_files

   @entries = io( q(path_to_directory) )->all_files( $level );

Like ->all( $level ) but returns only files

append

   io( q(path_to_file) )->append( $line1, $line2, ... );

Opens the file in append mode and calls "print" with the passed args

appendln

   io( q(path_to_file) )->appendln( $line, $line2, ... );

Opens the file in append mode and calls "println" with the passed args

assert

   $io = io( q(path_to_file) )->assert;

Sets the private attribute _assert to true. Causes the open methods to create the path to the directory before the file/directory is opened

assert_dirpath

   io( q(path_to_file) )->assert_dirpath;

Create the given directory if it doesn't already exist

assert_filepath

   io( q(path_to_file) )->assert_filepath;

Calls "assert_dirpath" on the directory part of the full pathname

assert_open

   $io = io( q(path_to_file) )->assert_open( $mode, $perms );

Calls "file" to default the type if its not already set and then calls "open" passing in the optional arguments

atomic

   $io = io( q(path_to_file) )->atomic;

Implements atomic file updates by writing to a temporary file and then renaming it on closure. This method uses the pattern in the _atomic_infix attribute to compute the temporary pathname

atomic_suffix

Syntatic sugar. See "atomix_infix"

atomic_infix

Defaults to B_* (prefix). The * is replaced by the filename to create a temporary file for atomic updates. If the value does not contain a * then it is appended to the filename instead (suffix). Attribute name _atomic_infix

basename

   $dirname = io( q(path_to_file) )->basename( @suffixes );

Returns the File::Basename basename of the passed path

binary

   $io = io( q(path_to_file) )->binary;

Sets binary mode

binmode

   $io = io( q(path_to_file) )->binmode( $layer );

Sets binmode to the given layer

block_size

Defaults to 1024. The default block size used by the "read" method

buffer

The internal buffer used by "read" and "write"

_build__dir_pattern

Returns the pattern that will match against the current or parent directory

canonpath

   $canonpath = io( '././path_to_file' )->canonpath;

Returns the canonical path for the object

catdir

Create a new IO directory object by concatenating this objects pathname with the one that is supplied

catfile

Create a new IO file object by concatenating this objects pathname with the one that is supplied

chmod

   $io = $io->chmod( q(0644) );

Changes the permission on the file to the selected value. Permission values can be eithe octal or string

chomp

   $io = io( q(path_to_file) )->chomp;

Causes input lines to be chomped when "getline" or "getlines" are called

chown

   $io = $io->chown( $uid, $gid );

Changes user and group ownership

clear

   $io->clear

Set the contents of the internal buffer to the null string

close

   $io->close;

Close the file or directory handle depending on type

If the temporary atomic file exists, renames it to the original filename. Unlocks the file if it was locked. Closes the file handle

copy

   $dest_obj = $io->copy( $destination_path_or_object );

Copies the file to the destination. The destination can be either a path or and IO object. Returns the destination object

deep

   @files = io( 'path_to_root_of_tree' )->deep->all_files

Changes the default level for the "all" methods to zero so that the whole directory tree is searched

delete

Deletes the atomic update temporary file if it exists. Then calls "close"

delete_tmp_files

   io( $tempdir )->delete_tmp_files( $template );

Delete temporary files for this process (temporary file names include the process id). Temporary files are stored in the $tempdir. Can override the template filename pattern if required

DEMOLISH

If this is an atomic file update calls the "delete" method. If the object is still open it calls the "close" method

dir

Initialises the current object as a directory

dirname

   $dirname = io( q(path_to_file) )->dirname;

Returns the File::Basename dirname of the passed path

empty

Returns true if the pathname exists and is zero bytes in size

encoding

   $io = io( q(path_to_file) )->encoding( $encoding );

Apply the given encoding to the open file handle and store it on the _encoding attribute

error_check

Tests to see if the open file handle is showing an error and if it is it "throw"s an eIOError

exists

Returns true if the pathname exists

file

Initializes the current object as a file

filename

Returns the filename part of pathname

filepath

Returns the directory part of pathname

filter

Takes a subroutine reference that is used by the "all" methods to filter which entries are returned. Called with $_ set to each pathname in turn. It should return true if the entry is wanted

getline

Asserts the file open for reading. Get one line from the file handle. Chomp the line if the _chomp attribute is true. Check for errors. Close the file if the autoclose attribute is true and end of file has been read past

getlines

Like "getline" but calls "getlines" on the file handle and returns an array of lines

_init

Sets default values for some attributes, takes two optional arguments; type and name

autoclose

Defaults to true. Attempts to read past end of file will cause the object to be closed

exception_class

Defaults to undef. Can be set to the name of an class that provides the "throw" method

io_handle

Defaults to undef. This is set when the object is actually opened

is_open

Defaults to false. Set to true when the object is opened

name

Defaults to undef. This must be set in the call to the constructor or soon after

type

Defaults to false. Set by the "dir" and "file" methods to dir and file respectively. The "dir" method is called by the "next" method. The "file" method is called by the "assert_open" method if the type attribute is false

io

Subroutine exported by default. Returns a new IO object

is_absolute

Return true if the pathname is absolute

is_dir

   $bool = io( q(path_to_file) )->is_dir;

Tests to see if the IO object is a directory

is_executable

   $bool = io( q(path_to_file) )->is_executable;

Tests to see if the IO object is executable

is_file

   $bool = io( q(path_to_file) )->is_file;

Tests to see if the IO object is a file

is_readable

   $bool = io( q(path_to_file) )->is_readable;

Tests to see if the IO object is readable

is_reading

Returns true if this IO object is in one of the read modes

is_writable

   $bool = io( q(path_to_file) )->is_writable;

Tests to see if the IO object is writable

length

Returns the length of the internal buffer

lock

   $io = io( q(path_to_file) )->lock;

Causes "_open_file" to set a shared flock if its a read an exclusive flock for any other mode

mkdir

   io( q(path_to_directory) )->mkdir;

Create the specified directory

mkpath

   io( q(path_to_directory) )->mkpath;

Create the specified path

next

Calls "dir" if the type is not already set. Asserts the directory open for reading and then calls "read_dir" to get the first/next entry. It returns an IO object for that entry

open

   $io = io( q(path_to_file) )->open( $mode, $perms );

Calls either "_open_dir" or "_open_file" depending on type. You do not usually need to call this method directly. It is called as required by "assert_open"

_open_dir

If the _assert attribute is true calls "assert_dirpath" to create the directory path if it does not exist. Opens the directory and stores the handle on the io_handle attribute

_open_file

Opens the pathname with the given mode and permissions. Calls "assert_filepath" if assert is true. Mode defaults to the mode attribute value which defaults to r. Permissions defaults to the _perms attribute value. Throws eCannotOpen on error. If the open succeeds "set_lock" and "set_binmode" are called

pathname

   $pathname = $io->pathname( $pathname );

Sets and returns then name attribute

perms

   $io = io( q(path_to_file) )->perms( $perms );

Stores the given permissions on the _perms attribute

print

Asserts that the file is open for writing and then prints passed list of args to the open file handle. Throws ePrintError if the print statement fails

println

   io( q(path_to_file) )->println( $line1, $line2, ... );

Calls "print" appending a newline to each of the passed list args that doesn't already have one

read

   $bytes_read = io( q(path_to_file) )->read( $buffer, $length );

Asserts that the pathname is open for reading then calls "read" on the open file handle. If called with args then these are passed to the "read". If called with no args then the internal buffer is used instead. Returns the number of bytes read

read_dir

Asserts that the file is open for reading. If called in an array context returns a list of all the entries in the directory. If called in a scalar context returns the first/next entry in the directory

rel2abs

   $path = io( q(relative_path_to_file) )->rel2abs( q(optional_base_path) );

Makes the pathname absolute. Returns a path

relative

Calls "abs2rel" without an optional base path

rmdir

Remove the director

rmtree

Remove the directory tree

seek

Seeks to the selected point in the file

separator

Set the record separator used in calls to getlines and chomp

set_binmode

Sets the currently selected binmode on the open file handle

set_lock

Calls "flock" on the open file handle

slurp

In a scalar context calls "all" and returns its value. In an array context returns the list created by splitting the scalar return value on the system record separator. Will chomp each line if required

splitdir

Proxy for "splitdir" in File::Spec

splitpath

Proxy for "splitpath" in File::Spec

stat

Returns a hash of the values returned by a "stat" call on the pathname

substitute

   $io = io( q(path_to_file) )->substitute( $search, $replace );

Substitutes $search regular expression for $replace string on each line of the given file

tempfile

Create a randomly named temporary file in the name directory. The file name is prefixed with the creating processes id and the temporary directory defaults to /tmp

throw

Exposes the throw method in the class exception class

touch

Create a zero length file if one does not already exist with given file system permissions which default to 0644 octal. If the file already exists update it's last modified datetime stamp

Delete the specified file

unlock

Calls flock on the open file handle with the LOCK_UN option to release the Fcntl lock if one was set. Called by the "close" method

utf8

Sets the current encoding to utf8

write

   $bytes_written = io( q(pathname) )->write( $buffer, $length );

Asserts that the file is open for writing then write the $length bytes from $buffer. Checks for errors and returns the number of bytes written. If $buffer and $length are omitted the internal buffer is used. In this case the buffer contents are nulled out after the write

Diagnostics

None

Configuration and Environment

None

Dependencies

namespace::clean
overload
File::DataClass::Constants
File::DataClass::Exception
Moose

Incompatibilities

On MSWin32 and Cygwin platforms there is a race condition when the atomic write option is used. This is caused by the filesystem which does not allow an open file to be renamed

Bugs and Limitations

There are no known bugs in this module. Please report problems to the address below. Patches are welcome

Acknowledgements

Larry Wall

For the Perl programming language

Ingy döt Net <ingy@cpan.org>

For IO::All from which I took the API and some tests

Author

Peter Flanigan, <Support at RoxSoft.co.uk>

License and Copyright

Copyright (c) 2012 Peter Flanigan. All rights reserved

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic

This program is distributed in the hope that it will be useful, but WITHOUT WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE

1 POD Error

The following errors were encountered while parsing the POD:

Around line 1562:

Non-ASCII character seen before =encoding in 'döt'. Assuming CP1252