Data(3)

NAME
File::Data - Regular expression interface to files

DESCRIPTION
Wraps all the accessing of a file into a convenient set of calls for reading and writing data, including a simple regex interface.

SYNOPSIS

        use File::Data;
        my $o_reg = File::Data->new('/etc/passwd');
        my @orig = $o_reg->read;
        $o_reg->append("appended:entry:4:A second name::etc::sh\n");
        $o_reg->replace('^(?:[^:]:){3}([^:]+):', 'replaced:entry:4:another name::etc::sh\n');
        $o_reg->prepend("prepended:entry:4:A first name::etc::sh\n");
        print 'new names: ' = $o_reg->search('(name.+):');
See the METHODS manpage and the EXAMPLES manpage.

EXPLANATION
The idea is to standardise accessing of files for repetitive and straight forward tasks, and remove the repeated and therefore error prone file access I have seen in many sites, where varying, (with equivalently varying success), methods are used to achieve essentially the same result - a simple search and replace and/or a regex match.

Approaches vary: One person may wish to know if a file exists, another wishes to know whether the target is a file, or if it is readable, or writable and so on. Sometimes, in production code even (horror), file's are opened without any checks of whether the open was succesful. Then there's a loop through each line to find the first or many patterns to read and/or replace. With a failure, normally the only message is 'permission denied', is that read or write access, does the file even exist? etc.

This module attempts to provide a plain/generic interface to accessing a file's contents. This will not suit every situation, but I have included some examples which will hopefully demonstrate that it may be used in situations where people would normally go through the same procedure for the umpteenth time to get at the same data.

One last thing - I'm sure this could be made much more efficient, and I'll be very interested to try and incorporate any suggestions to that effect. Note though that the intention has been to create a simple moderately consistent interface, rather than a complicated one. Sometimes it's better to roll your own, and sometimes you don't have to reinvent the wheel - TMTOWTDI.

# ================================================================

METHODS
Create a new File::Data object (default read-write permissions).

        my $o_rw = File::Data->new($filename);  # read-write
        my $o_ro = File::Data->new($filename, 'ro');    # read-only
Theoretically you can mix and match your read and writes so long as you don't open read-only.

        my $o_reg    = File::Data->new($file);
        my @partial  = $o_reg->search($pattern);
        my $i_cnt    = $o_reg->replace($search, $replace);
Note that if you open a file read-only and then attempt to write to it, that will be regarded as an error, even if you change the permissions in the meantime. Simple wrapper for method calls, returning the object, so that you can chain them, prints the results so you can catch them on STDOUT.

        my $o_reg = $o_reg->do('insert', @insertargs)->do('append', @appendargs)->do('read');
Read all data from file

        my @data = $o_reg->read;
Write data to file

        my @written = $o_reg->write;
Prepend to file

        my @prepended = $o_reg->prepend(\@lines);
Insert data at line number, starting from '0'

        my @inserted = $o_reg->insert($i_lineno, \@lines);
Append to file

        my @appended = $o_reg->append(\@lines);
Retrieve data out of a file, simple list of all matches found are returned.

Note - you must use capturing parentheses for this to work!

my @addrs = $o_reg->search('/^(.*\@.*)$/');

my @names = $o_reg->search('/^(?:[^:]:){4}([^:]+):/'); Replace data in a 'search and replace' manner, returns the final data.

        my @data = $o_reg->replace($search, $replace);
        my @data = $o_reg->replace(
                q|\<a href=(['"])([^$1]+)?$1| => q|'my.sales.com'|,
        );
This is simple, in that you can do almost anything in the search side, but the replace side is a bit more restricted, as we can't effect the replacement modifiers on the fly.

If you really need this, perhaps (?{}) can help? Returns File::stat object for the file.

        print 'File size: '.$o_reg->stat->size;
sub xfstat {
    my $self = shift;
    my $file = shift || '_';

        # print "file($file) stat: ".Dumper(stat($file));
        # return stat($file);
}
Do something ...?

        my @res = $o_reg->dummy(@args);

# ================================================================

VARIABLES
Various variables may be set affecting the behaviour of the module. Set to 0 (default) or 1 for debugging information to be printed on STDOUT.

        $File::Data::DEBUG = 1;
Will die if there is any failure in accessing the file, or reading the data.

Default = 0 (don't die - just warn);

        $File::Data::FATAL = 1; # die
Will return a reference, not a list, useful with large files.

Default is 0, ie; methods normally returns a list.

Hopefully future versions of perl may return a reference if you request one, but as this is not supported generically yet, nor do we, so we require the variable to be set. There may be an argument to make this a reference by default, feedback will decide.

        $File::Data::REFERENCE = 1;
        my $a_ref = $o_reg->search('.*');
        print "The log: \n".@{ $a_ref };
Where regex's are used, default behaviour is to treate the entire file as a single scalar string, so that, for example, /cgms matches are effective.

Unset if you don't want this behaviour.

        $File::Data::STRING = 0; # per line
File will be opened read-write (insert() compatible) unless this variable is set explicitly or given via new(). In either case, unless it is one of our keys declared below, it will be passed on to FileHandle and otherwise not modified.

Read-only permissions may be explicitly set using one of the following keys:

        $File::Data::PERMISSIONS = 'ro'; # or readonly or <
Or, equivalently, for read-write (default):

        rw readwrite +<
Start from the end of the file.

The default is 0 ie; start at the start of the file...

        $File::Data::REVERSE = 1; # tac

# ================================================================

PRIVATE
Private methods not expected to be called outside this class, and completely unsupported.

Expected to metamorphose regularly - do not call these directly - you have been warned! Variable get/set method

        my $get = $o_reg->_var($key);           # get
        my $set = $o_reg->_var($key, $val);     # set
Print given args on STDOUT

        $o_reg->_debug($msg) if $File::Data::DEBUG;
Return dumped env and object key and values

        print $o_reg->_vars;
Get/set error handling methods/objects

        my $c_sub = $o_reg->_err('insert'); # or default
By default prints error to STDERR, will croak if File::Data::FATAL set.

See the EXAMPLES manpage for info on how to pass your own error handlers in. Maps file

        my $file = $o_reg->_mapfile($filename);
Maps given permissions to appropriate form for FileHandle

        my $perms = $o_reg->_mapperms('+<');
Map error handlers, if given

        my $h_errs = $o_reg->_maperrs(\%error_handlers);
Mark the entering of a special section, or state

        my $entered = $o_reg->enter('search');
Mark the leaving of a special section, or state

        my $left = $o_reg->_leave('search');
Get and set FileHandle.

Returns undef otherwise.

        my $FH = $o_reg->_fh($FH);

# ================================================================

UTILITY
The following utility methods return integer values

        1 = success
        0 = failure
Setup object, open a file, with permissions.

        my $i_ok = $o_file->_init($file, $perm, $h_errs);
Checks the args for existence and appropriate permissions etc.

        my $i_isok = $o_reg->_check_access($filename, $permissions);
Open the file

        my $i_ok = $o_reg->_open;
Lock the file

        my $i_ok = $o_reg->_lock;
Unlock the file

        my $i_ok = $o_reg->unlock;
Close the filehandle

        my $i_ok = $o_reg->_close;

SPECIAL
Any unrecognised function will be passed to the FileHandle object for final consideration, behaviour is then effectively 'o_reg ISA FileHandle'.

        $o_reg->truncate;

EXAMPLES
Typical construction examples:

        my $o_rw = File::Data->new($filename, 'rw');
        my $o_ro = File::Data->new($filename, 'ro');
Failure is indicated by an error routine being called, this will print out any error to STDERR, unless warnings are declared fatal, in which case we croak. You can register your own error handlers for any method mentioned in the the METHOD manpage section of this document, in addition is a special init call for initial file opening and general setting up.

Create a read-write object with a callback for all errors:

        my $o_rw = File::Data->new($filename, 'ro', {
                'error'         => \&myerror,
        });
Create a read-only object with a separate object handler for each error type:

        my $o_rw = File::Data->new($filename, 'rw', {
                'error'         => $o_generic->error_handler,
                'insert'        => $o_handler->insert_error,
                'open'          => $o_open_handler,
                'read'          => \&carp,
                'write'         => \&write_error,
        });
From the command line:

perl -MFile::Data -e "File->Data->new('./test.txt')->insert('123', '456')";

If you still have problems, mail me the output of

    make test TEST_VERBOSE=1

AUTHOR
Richard Foley <C> richard.foley@rfi.net 2001

For those that are interested, the docs and tests were (mostly) written before the code.