NAME

TIe::File::Hashify - Parse a file and tie the result to a hash.

SYNOPSIS

use Tie::File::Hashify;

my %rc;
my $path = "$ENV{HOME}/.some.rc";

# Parse lines like 'foo = bar':
sub parse { $_[0] =~ /^\s*(\S+)\s*=\s*(.*?)\s*$/ };

# Format pairs as 'key = value':
sub format { "$_[0] = $_[1]" };

tie(%rc, 'Tie::File::Hashify', $path, \&parse, \&format);

print "option 'foo' = $rc{foo}\n";

# Add new option.
$rc{bar} = 'moo';

# Save file.
untie %rc;

DESCRIPTION

This module helps parsing simple text files and mapping it's contents to a plain hash. It reads a file line by line and uses a callback or expression you provide to parse a key and a value from it. The key/value pairs are then available through the generated hash. You can also provide another callback or format string that formats a key/value pair to a line to be stored back to the file.

METHODS

tie(%hash, $path, \&parse, \&format)

The third argument (after the hash itself and the package name of course) is the path to a file. The file does not really have to exist, but using a path to a non-existent file does only make sense if you provide a format-callback to write a new file.

The third argument is used for parsing the file. It may either be code reference, which will be called with a line as argument and should return the key and the value for the hash element; or it may be a string or compiled regular expression (qr//). The expression will be applied to every line and $1 and $2 will be used as key/value afterwards.

The fourth argument is used for formatting the hash into something that can be written back to the file. It may be a code reference that takes two arguments (key and value) as arguments and returns a string (without trailing line-break - it will be added automatically), or a format string that is forwarded to sprintf together with the key and the value.

All arguments (path, parse, format) each may be omitted / undef. If you omit all of them, you get a plain normal hash.

COPYRIGHT

Copyright (C) 2008 by Jonas Kramer <jkramer@cpan.org>. Published under the terms of the Artistic License 2.0.