0

I am in the process of repetitively loading a series of hashes (written in JSON) from a configuration file, then making sure that none of them changed.

So, if the configuration file is something like this:

  "sources" : [
    {
      "source_name": "A",
      "interval"   : 6,
      "params"     : {
        "what" : "testA"
      }
    },
    {
      "source_name": "B",
      "interval"   : 6,
      "params"     : {
        "what" : "testB"
      }
    }
  ]

And then in the next run it changed to this (only swapping the first two lines, effectively nothing has changed):

  "sources" : [
    {
      "interval"   : 6,
      "source_name": "A",
      "params"     : {
        "what" : "testA"
      }
    },
    {
      "source_name": "B",
      "interval"   : 6,
      "params"     : {
        "what" : "testB"
      }
    }
  ]

I should be able to detect that nothing has changed.

For that reason, I might Digest::SHA the stringification of the hash. So, the question is, is Data::Dumper consistent? Like, if I pass two identical hashes, will I always get an identical string out? I've already played a bit with changing the order of the keys, and it seems consistent; but of course this is not a proof.

And if not, any advice on how to do that?

3 Answers 3

2

I believe Data::Compare is what you should be using.

So, the question is, is Data::Dumper consistent? Like, if I pass two identical hashes, will I always get an identical string out?

Hashes are not ordered, so I wouldn't rely on that, but you can sort before printing if that is what you are after.

1

You can use $Data::Dumper::Sortkeys = 1; to make sure the keys were sorted when dump out;

use Data::Dumper;

$Data::Dumper::Sortkeys = 1;
my $hash = {b => 2, a => 1, };
print Dumper $hash; 

if you want to compare two hashes whether they have the same structure, you can use Test::Deep::NoTest.

use Test::Deep::NoTest;

my $hash_1 = {a => 1, b => 2 };
my $hash_2 = {b => 2, a => 1 };
if(eq_deeply($hash_1, $hash_2)){
    println "same!\n";
}
0

Is Data::Dumper consistent?

Not unless you tell it to be. You can do this by setting Sortkeys.

my $dumper = Data::Dumper->new( $data );
$dumper->Sortkeys(1);
print $dumper->Dump;

This is because hashes have no inherent order. In older versions of Perl the order of hashes with the same key sets would be consistent, but that is no longer reliable.

Alternatively you can use perl5i and its diff method.

use perl5i::2;

my $a = { foo => "bar" };
my $b = { foo => "barr" };

my $diff = $a->diff($b);
if( keys %$diff ) {
    say "There are differences.";
    say $diff->mo->as_json;
}
else {
    say "No differences.";
}

Or use perl5i's meta object checksum method.

use perl5i::2;
say "No differences" if $a->mo->checksum eq $b->mo->checksum;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.