将哈希按第一个键到最后一个键排序(Perl)

4

我有以下哈希(散列),我希望将其保持在我设置的顺序中;这是否可能?如果不行,是否存在任何替代方案?

my %hash = ('Key1' => 'Value1', 'Key2' => 'Value2', 'Key3' => 'Value3');

我需要编写自定义排序子程序吗?有哪些选项?

谢谢!


2
不,数组也不会保留插入顺序。$a[1]="a"; $a[0]="b"; print "@a\n"; 将输出 b a 。无论是数组还是哈希表都会按照物理位置返回元素。 - ikegami
你为什么需要对关联数组(哈希)进行排序? - gaussblurinc
5个回答

8

我本来希望不需要外部库就能实现,但是这个方法也可以解决问题。 已经测试并且可行,谢谢! - user1807879

2
请参考Tie::Hash::Indexed。引用其摘要:
use Tie::Hash::Indexed;

tie my %hash, 'Tie::Hash::Indexed';

%hash = ( I => 1, n => 2, d => 3, e => 4 );
$hash{x} = 5;

print keys %hash, "\n";    # prints 'Index'
print values %hash, "\n";  # prints '12345'

1

1
一种可能性是像处理数组一样指定键。
 for (0..$#a) {  # Sorted array keys
     say $a[$_];
 }

 for (sort keys %h) {  # Sorted hash keys
     say $h{$_};
 }

 for (0, 1, 3) {  # Sorted array keys
     say $h{$_};
 }

 for (qw( Key1 Key2 Key3 )) {  # Sorted hash keys
     say $h{$_};
 }

您也可以按以下方式获取已排序的值:

 my @values = @h{qw( Key1 Key2 Key3 )};

0

这取决于您如何访问数据。如果您只想存储它们并访问最后/第一个值,则始终可以将哈希放入数组中并使用push()和pop()。

#!/usr/bin/env perl

use strict;
use warnings;

use v5.10;

use Data::Dumper;

my @hashes;

foreach( 1..5 ){
    push @hashes, { "key $_" => "foo" };
}


say Dumper(\@hashes);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接