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


        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 => \&parse, format => \&format);

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

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

        # Save file.
        untie %rc;


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.


tie(%hash, 'Tie::File::Hashify', $path, %options)

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.

After the second argument, a list of options may/should follow:


Either a code reference, which will be called with a line as argument and should return the key and the value for the hash element; or 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.


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


If this is true, changing the hash will make it croak, and the content will not be written back to the file.

All arguments are optional. If you don't give any arugments, you get a plain normal hash.


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

"read-only" functionality by Marco Emilio Poleggi.