我想要创建数据结构的签名:

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

目标应该是,如果数据结构发生变化,签名也应如此。

有没有确定的方法来做到这一点?

有帮助吗?

解决方案

执行此操作的最佳方法是使用深层结构序列化系统,例如可存储。具有相同数据的两个结构将产生相同的可存储输出blob,因此可以对它们进行比较。

#!/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;

......并证明相反:

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

print "no match" if $one_s ne $two_s;

其他提示

我认为您正在寻找的是哈希函数。我会推荐这样的方法:

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

函数哈希可以是任何哈希函数,例如来自的函数md5文摘:: MD5

使用 Storable :: nstore将其转换为二进制表示形式,然后计算出校验和(例如使用摘要模块)。

这两个模块都是核心模块。

Digest::MD5->new->add(
  Data::Dumper->new([$structure])
   ->Purity(0)
   ->Terse(1)
   ->Indent(0)
   ->Useqq(1)
   ->Sortkeys(1)
   ->Dump()
)->b64digest();

我认为您要找的字是“哈希”

基本上,您将数据结构放在一个函数中,该函数从中生成一个相当独特的值。这个值将是你的签名。

你不能使用对象而不是结构吗?这样你就可以看到一个对象是否是一个类型的实例,而不必比较哈希等等。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top