perl,一个哈希,输出重复的问题
@a=qw/hehehahazz123456&&hehe/;$count{$_}++foreach@a;foreach$word(sort@a){print"$wordh...
@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别动) 展开
$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别动) 展开
3个回答
展开全部
foreach $word (sort keys %count){
print "$word has been appreared $count{$word} times! \n"
}
把你的输出改成这样不就好了。否则你基本就没有用hash啊。。。hash的好处不就是同名的只会出现一次么。直接输出你的hash %count就可以了。
print "$word has been appreared $count{$word} times! \n"
}
把你的输出改成这样不就好了。否则你基本就没有用hash啊。。。hash的好处不就是同名的只会出现一次么。直接输出你的hash %count就可以了。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
还是再加个计数器%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}++;
}
}
#!/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}++;
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询