简体   繁体   English

如何在Perl中使用哈希生成唯一ID?

[英]How can I generate a unique ID using a hash in Perl?

I am writing a message transfer program between multiple clients and server. 我正在多个客户端和服务器之间编写一个消息传输程序。

I want to generate a unique message ID for every message. 我想为每条消息生成一个唯一的消息ID。 It should be generated by the server and returned to the client. 它应该由服务器生成并返回给客户端。

For message transfer, I am using a hash data structure, for example: 对于消息传输,我使用哈希数据结构,例如:

{
api => POST,
username => sganesh,
pass => "pass",
message => "hai",
time => "current_time",
}

I want to generate a unique ID using this hash. 我想使用此哈希生成唯一ID。

I have tried several approaches, MD5 and freeze but these give unreadable IDs. 我尝试了几种方法,MD5和冻结,但这些方法提供了不可读的ID。 I want some meaningful or readable unique IDs. 我想要一些有意义或可读的唯一ID。

I have thought we can use microseconds to differentiate between the IDs but here the problem is multiple clients. 我以为我们可以使用微秒来区分ID,但问题是多个客户端。

In any situation the IDs should be unique. 在任何情况下,ID都应该是唯一的。

Can anyone help me out of this problem? 任何人都可以帮我解决这个问题吗?

Thanks in advance. 提前致谢。

I suspect you don't want to do what you are asking, but you can do it. 我怀疑你不想做你想要的,但你可以做到。

  • Take the hash key/values and flatten them to an array @foo = (%foo) . 获取哈希键/值并将它们展平为数组@foo = (%foo)

  • MD5 the array to get an ID code - use md5_base64(@foo) if you want it to be 7bit (human readable). MD5数组获取ID代码 - 如果你希望它是7bit(人类可读),请使用md5_base64(@foo) )。

  • Remember that hashes are not ordered, so you need sort @foo the array if you want it to be repeatable. 请记住,散列不是有序的,因此如果希望数组可重复,则需要sort @foo数组进行sort @foo

In code, something like: 在代码中,类似于:

use Digest::MD5 qw(md5_base64);

my $foo = {
    api => POST,
    username => sganesh,
    pass => "pass",
    message => "hai",
    time => "current_time",
};

my $id = md5_base64(sort %$foo); # in my case eRR9QzGN1n+nIl1TDmclEA

To be honest, I think you are better off generating a unique random ID (a token) and giving it to the client to return to you, but then from your question, I don't know your motivation. 说实话,我认为你最好生成一个独特的随机ID(一个令牌)并将其交给客户返回给你,但是从你的问题来看,我不知道你的动机。

This sounds like a job for Data::UUID . 这听起来像是Data :: UUID的工作

Furthermore, the unique ID is for a computer. 此外,唯一ID用于计算机。 You can abstract that anyway that you like for the humans. 无论如何,你可以抽象出你喜欢的人类。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM