Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi guys (gals implicitly included),

I am a quick question that I have been unable to find an answer to via google or the cookbook.

I am using Config::Auto which appears to return a reference to an anonymous hash.
my $SETS = Config::Auto::parse( '/path/file.conf' ); print Dumper( $SETS ); $VAR = { 'entryA' => { anonymous hash } 'entryB' => { anonymous hash } };
I want to modify this to read multiple config files as follows:
my @files = </path/to/files/*>; my $SETS = Config::Auto::parse( $_ ) foreach @files;
Obviously only the last entry ends up in $SETS. Is there an elegant way to achieve the above. There seems to be plenty of documentation on how to achieve this for hashes, arrays, or even arrays of references but just not the above. (It is also quite possible that I do not really understand what exactly I am dealing with as I am not really a programmer.)

Any help would be greatly appreciated.

Cheers,
Patrick

Replies are listed 'Best First'.
Re: combining multiple hashrefs
by clinton (Priest) on Jul 09, 2007 at 09:47 UTC
    Use Config::Loader Config::Merge - it handles exactly this problem. It can:
    • read files containing YAML, JSON, XML, INI, Perl and Config::General data
    • recurse through a directory tree loading the config (hash or array) at the correct point in the config hash
    • merge values for local config into the tree, to allow you to handle development and production environments safely

    Clint

    Update: Changed the module name to reflect its new name

      Thanks for this. I'm not going to use it this time round as this is a major change and would require re-testing etcetera to ensure that the config syntax is parsed as expected; however, I will stick this in the back of my mind for future projects. Cheers, Patrick.
Re: combining multiple hashrefs
by varian (Chaplain) on Jul 09, 2007 at 06:28 UTC
    Collect the references in an array and create your own hash from them:
    my @configs; push @configs, Config::Auto::parse( $_ ) foreach @files; my $SETS = { map {%$_} @configs };
    You could combine the above into a oneliner yet that might obfuscate the code a bit.
      Thanks to all those who replied. I appreciate you help. I am planning to implement the above code as it is closest to what I was trying to achieve (in terms of being integrated into the loop). Patrick.
Re: combining multiple hashrefs
by EvanCarroll (Chaplain) on Jul 09, 2007 at 05:45 UTC
    How awkward for you to say that when Hash::Merge only takes hash refs.
    my %c = %{ merge( \%a, \%b ) };
    It has pretty intelligent defaults, probably will do what you want off the shelf.


    Evan Carroll
    www.EvanCarroll.com