如何按照添加到散列的顺序打印散列的键/值对.
例如:
%hash = ("a","1","b","2","c","3"); while (($key,$value) = each %hash) { print "$key","$value\n"; }
以上结果如下:
c3 a1 b2
a1 b2 c3
提前致谢!
解决方法
由于您不想使用任何提到的模块(Tie :: IxHash和Tie :: Hash :: Indexed),并且由于哈希值为
unordered collections(如前所述),因此您必须在插入值时存储此信息:
#!/usr/bin/perl use warnings; use strict; my %hash; my %index; #keep track of the insertion order my $i=0; for (["a","1"],["b","2"],["c","3"]) { #caveat: you can't insert values in your hash as you did before in one line $index{$_->[0]}=$i++; $hash{$_->[0]}=$_->[1]; } for (sort {$index{$a}<=>$index{$b}} keys %hash) { #caveat: you can't use while anymore since you need to sort print "$_$hash{$_}\n"; }
这将打印:
a1 b2 c3