禁止 Perl 哈希在创建时进行排序
我使用以下命令在 perl 中创建了一个哈希:
%columns = ("ID" , 10, "Time" , 25, "Cluster" , 25, "Type" , 10, "Hostname" , 30, "Service" , 25, “评论”,50);
我不希望以任何方式修改排序顺序。然而,Perl 主动为我对它们进行排序。
$VAR1 = 'ID';
$VAR2 = 10;
$VAR3 = 'Hostname';
$VAR4 = 30;
$VAR5 = 'Type';
$VAR6 = 10;
$VAR7 = 'Time';
$VAR8 = 25;
$VAR9 = 'Comment';
$VAR10 = 50;
$VAR11 = 'Cluster';
$VAR12 = 25;
$VAR13 = 'Service';
$VAR14 = 25;
我怎样才能避免这种行为?
已解决:
tie(%{$monstatus_settings{"comments"}->{"columns"}}, "Tie::IxHash", "ID" => 10, "Time" => 25, "Cluster" => 25, "Type" => 10, "Hostname" => 30, "Service" => 25, "Comment" => 50);
I created a hash in perl with this command:
%columns = ("ID" , 10, "Time" , 25, "Cluster" , 25, "Type" , 10, "Hostname" , 30, "Service" , 25, "Comment" , 50);
I do not want the sort order modified in any way. However, Perl has taken it upon itself to sort them for me.
$VAR1 = 'ID';
$VAR2 = 10;
$VAR3 = 'Hostname';
$VAR4 = 30;
$VAR5 = 'Type';
$VAR6 = 10;
$VAR7 = 'Time';
$VAR8 = 25;
$VAR9 = 'Comment';
$VAR10 = 50;
$VAR11 = 'Cluster';
$VAR12 = 25;
$VAR13 = 'Service';
$VAR14 = 25;
How can I avoid this behavior?
Resolved:
tie(%{$monstatus_settings{"comments"}->{"columns"}}, "Tie::IxHash", "ID" => 10, "Time" => 25, "Cluster" => 25, "Type" => 10, "Hostname" => 30, "Service" => 25, "Comment" => 50);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能。哈希值是显式无序的(实际上,按键的计算哈希值排序;这就是它们是哈希值的原因)。如果您想保持顺序,请使用列表。或者使用两者,列表是哈希键的有序列表。
You can't. Hashes are explicitly unordered (actually, ordered by the computed hash for the key; that's why they're hashes). If you want to preserve order, use lists. Or use both, with the list being an ordered list of hash keys.