perl – 如何按照添加到哈希的顺序打印哈希的元素

前端之家收集整理的这篇文章主要介绍了perl – 如何按照添加到哈希的顺序打印哈希的元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何按照添加到散列的顺序打印散列的键/值对.

例如:

%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

猜你在找的Perl相关文章