Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a repeatable signature of a data structure?

I have a situation where I want to create a signature of a data structure:

my $signature = ds_to_sig(
  { foo   => 'bar',
    baz   => 'bundy',
    boing => undef,
    number => 1_234_567,
  }
);

The aim should be that if the data structure changes then so should the signature.

Is there an established way to do this?

like image 678
EvdB Avatar asked Oct 20 '08 13:10

EvdB


2 Answers

I think what you're looking for is a hash function. I would recommend an approach like this:

use Storable;
$Storable::canonical = 1;
sub ds_to_sig {
    my $structure = shift;
    return hash(freeze $structure);
}

The function hash can be any hash function, for example the function md5 from Digest::MD5

like image 164
Leon Timmermans Avatar answered Sep 20 '22 12:09

Leon Timmermans


The best way to do this is to use a deep-structure serialization system like Storable. Two structures with the same data will produce the same blob of Storable output, so they can be compared.

#!/usr/bin/perl

use strict;
use warnings;

use Storable ('freeze');

$Storable::canonical = 1;

my $one = { foo => 42, bar => [ 1, 2, 3 ] };
my $two = { foo => 42, bar => [ 1, 2, 3 ] };

my $one_s = freeze $one;
my $two_s = freeze $two;

print "match\n" if $one_s eq $two_s;

...And to prove the inverse:

$one = [ 4, 5, 6 ];
$one_s = freeze $one;

print "no match" if $one_s ne $two_s;
like image 31
friedo Avatar answered Sep 20 '22 12:09

friedo