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

Hi All, I recently ran into a situation where I have to check if the two hash references are similar in structure. Something like,

my $ds1 = { part => { id => 123, name => wheel} } my $ds2 = { component => {id => 123, name => stereo} }

The above two data structures look similar in structure. By this I mean, both of them are hash references with key as strings and values again as hash references

Any suggestions on how to tackle this..

Many thanks D
  • Comment on Interesting problem on perl data structure

Replies are listed 'Best First'.
Re: Interesting problem on perl data structure
by BioLion (Curate) on Oct 12, 2009 at 14:12 UTC

    You can test what a reference points to with ref, and test keys with either regexes or with the functions provided by Data::Types (is_string etc...). Data::Schema, once you get your head round it, can be used to ensure that a datastructure conforms to a particular 'look' or schema.

    So if you have a general 'are they similar??' question then go for Data::Types and some kind of datastructure crawler, maybe in parallel on the two structures, but if you want to know if both conform to a particular structure then try Data::Schema. I guess it is up to you to define what you consider makes the structures 'similar'... HTH.

    Update: SpAG...

    Just a something something...
Re: Interesting problem on perl data structure
by jettero (Monsignor) on Oct 12, 2009 at 14:02 UTC
    I usually tackle this with Data::Dumper. I suspect there's a better way if you need it efficient. But in module tests, where I actually do this, it's ok.
    use Data::Dumper; $Data::Dumper::Sortkeys = 1; $Data::Dumper::Indent = 0; if( Dumper($struct1) eq Dumper($struct2) ) { warn "same!" } else { warn "not same. :(" }
    Oh, wait, this won't help at all. I missed the word similar. Nevermind.

    -Paul

      BTW, Test::More's is_deeply() can be used to test data structure equivalence (though not, as you point out, the OP's 'similar').
Re: Interesting problem on perl data structure
by planetscape (Chancellor) on Oct 12, 2009 at 18:06 UTC
Re: Interesting problem on perl data structure
by ctilmes (Vicar) on Oct 12, 2009 at 16:51 UTC
    Data::Rx is another "data structure schema validation" module that can be used to check the two data structures independently against a schema.