如何保持我添加到Perl哈希的密钥顺序?

前端之家收集整理的这篇文章主要介绍了如何保持我添加到Perl哈希的密钥顺序?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在以下程序中使用散列值计算其发生次数后,如何维护实际列表的顺序?例如,< DATA>是 @H_502_2@a b e a c d a c d b etc.

使用哈希,我计算每个元素的发生。

我想要的是:

@H_502_2@a 3 b 2 e 1 c 2 d 2

但以下程序另外显示

@H_502_2@my (%count,$line,@array_1,@array_2); while ($line = <DATA>) { $count{$line}++ if ( $line =~ /\S/ ); } @array_1 = keys(%count); @array_2 = values(%count); for(my $i=0; $i<$#array_1; $i++) { print "$array_1[$i]\t $array_2[$i]"; }

解决方法

哈希没有订购,但像往常一样,CPAN提供了一个解决方案: Tie::IxHash @H_502_2@use Tie::IxHash; my %count; tie %count,'Tie::IxHash'; while ($line = <DATA>) { $count{$line}++ if ( $line =~ /\S/ ); } while( my( $key,$value)= each %count) { print "$key\t $value"; }

猜你在找的Perl相关文章