perl,一个哈希,输出重复的问题

@a = qw /hehe haha zz 123 456 && hehe/;
$count{$_}++ foreach @a ;
foreach $word (sort @a){
print "$word has been appreared $count{$word} times! \n"
}
运行程序:
root@luis-VirtualBox:~# ./perl.pl
&& has been appreared 1 times!
123 has been appreared 1 times!
456 has been appreared 1 times!
haha has been appreared 1 times!
hehe has been appreared 2 times!
hehe has been appreared 2 times!
zz has been appreared 1 times!

那个hehe打印了两次,我不想要重复输出,能不能修改程序只打印一次hehe ? (保持@a中的两个hehe别动)

@a = qw /hehe haha zz 123 456 && hehe/;
$count{$_}++ foreach @a ;
foreach $word (sort keys %count){ #--这里如果你遍历数组那么还是会输出重复,遍历hash就只有唯一的key
print "$word has been appreared $count{$word} times! \n"
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2012-04-11
foreach $word (sort keys %count){
print "$word has been appreared $count{$word} times! \n"
}
把你的输出改成这样不就好了。否则你基本就没有用hash啊。。。hash的好处不就是同名的只会出现一次么。直接输出你的hash %count就可以了。
第2个回答  2012-04-12
还是再加个计数器%temp吧:

#!/usr/bin/perl

use strict;
use warnings;

my %count = ();
my %temp = ();

my @a = qw /hehe haha zz 123 456 && hehe/;

$count{$_}++ foreach @a ;

foreach my $word (sort @a){
if(! $temp{$word}){
print "$word has been appreared $count{$word} times! \n";
$temp{$word}++;
}
}
相似回答