如何维护添加到 Perl 哈希的键的顺序? [英] How can I maintain the order of keys I add to a Perl hash?

查看:32
本文介绍了如何维护添加到 Perl 哈希的键的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在以下程序中使用哈希计算实际列表的出现次数后保持其顺序?例如,

How can I maintain the order of actual list after counting its occurrence using a hash in the following program? For example, <DATA> are

a
b
e
a
c 
d 
a
c
d
b
etc.

使用哈希,我计算了每个元素的出现次数.

Using hash, i counted the occurrence of each element.

我想要的是:

a  3
b  2
e  1
c  2
d  2

但下面的程序向我展示了其他情况.

but the following program shows me otherwise.

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]	 $array_2[$i]";
}

推荐答案

Hashes 不是有序的,但是像往常一样,CPAN 提供了一个解决方案:领带::IxHash

Hashes are not ordered, but as usual, CPAN offers a solution: Tie::IxHash

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	 $value"; 
}

这篇关于如何维护添加到 Perl 哈希的键的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆