我试图接受用户输入,例如4 2 1 4并将其存储到数组中。然后循环遍历数组,查找重复项以存储到哈希表中。
#!/usr/bin/perl -w
print "Enter numbers into hash table :";
my @num = <STDIN>;
my %hash;
foreach $x (@num){
my $count =1;
foreach $y(@num){
if($x == $y){
my $count++;
$hash{'$x'} = $count;
}
}
}
map{print "$_\t$hash{$_}\n"}keys %hash;
我希望结果如下: 1 1 2 1 4 2 实际结果,我只是继续输入数字,在我点击进入程序后继续要求更多输入。我点击了CTRL D,没有任何反应。
答案 0 :(得分:2)
可能会做得更好,但我会这样做:
use strict;
use warnings;
use Data::Dumper;
my $numbers;
print "Enter numbers and finish with CTRL-D\n";
while(my $line = <STDIN>) {
$numbers->{$_}++ for ( $line =~ m/(\b\d+\b)/g );
}
print Dumper $numbers;
答案 1 :(得分:2)
您的代码存在很多问题,我没有时间去探索它们
我希望为您提供有效的解决方案
#!/usr/bin/perl
use strict;
use warnings 'all';
my %counts;
print "Enter numbers into counts table: ";
++$counts{$_} for split ' ', <STDIN>;
print "$_\t$counts{$_}\n" for keys %counts;
E:\Perl\source>count.pl
Enter numbers into counts table: 4 2 1 4
1 1
2 1
4 2