perl – 如何按照添加到哈希的顺序打印哈希的元素
发布时间:2020-12-15 23:31:12 所属栏目:大数据 来源:网络整理
导读:如何按照添加到散列的顺序打印散列的键/值对. 例如: %hash = ("a","1","b","2","c","3");while (($key,$value) = each %hash) { print "$key","$valuen";} 以上结果如下: c3a1b2 我正在寻找一种方法来打印以下内容: a1b2c3 提前致谢! 解决方法 由于您不
如何按照添加到散列的顺序打印散列的键/值对.
例如: %hash = ("a","1","b","2","c","3"); while (($key,$value) = each %hash) { print "$key","$valuen"; } 以上结果如下: 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |