gnu@perl has asked for the wisdom of the Perl Monks concerning the following question:

I have a situation where I need to process some config files. The files are normally used in a ksh program for sourcing vars to the current env. In my program there is no need for them to be brought into the %ENV, I just need the key/value pairs. This part is easy.

What I would like to do is have a hash, say %basehash, that contains the same keys as in the config file. BTW, the keys will always be the same in the config files. In %basehash I would like to have the values set to a regex that describes what the value should look like in the actual config file. I would then like to load the config file into a hash, say $confighash, splitting on the '=' and making the LHS the key and the RHS the value.

Now, I would like to say something like 'if (%confighash == %basehash)'. I know it's not that simplistic, but it gets my idea across. What I don't what to do if I can avoid it is loop over one comparing it to the like key/value in the other.

??????
TIA, Chad.

Replies are listed 'Best First'.
Re: Comparing hashes
by rnahi (Curate) on Jun 06, 2003 at 17:58 UTC

    This question has been asked before, several times.

    Check Super Search for titles containing "compar hash" and you'll get a roomful.

    I would recommend starting with this recent node.

    For the impatient, here's a quick recipe (not the best one, but short nonetheless).

    print "different" if (join('/',sort keys %hash1) ne join('/',sort keys %hash2)) or ( join('/',sort values %hash1) ne join('/',sort values %hash2))
Re: Comparing hashes
by DamnDirtyApe (Curate) on Jun 06, 2003 at 16:06 UTC
    perldoc -q test hash equal

    This shows a rather interesting way of comparing two hashes together.

    Update: Link to relevant section of perlfaq4.


    _______________
    DamnDirtyApe
    Those who know that they are profound strive for clarity. Those who
    would like to seem profound to the crowd strive for obscurity.
                --Friedrich Nietzsche
Re: Comparing hashes
by gnu@perl (Pilgrim) on Jun 06, 2003 at 16:12 UTC

    OK, my response to my own question. After a little more thought I realized that you cannot directly compare two hashes without looping through the keys and checking. This is due to the fact that the two hashes will never have the same layout (just the way hashes work).

    There are some methods using Storable, but they are just as unreliable depending on what type of data you are holding in the hash (floating point problems, etc). The best and most reliable method I can think of is to iterate over the %confighash and check the corresponding values of each key with the regex held in the %confighash under the same key name.

    If someone knows a better, shorter more efficient way please let me know.

    Thanks again for everyone's time.