我想每行最多打印10个结果,然后在10之后强制换行。我该怎么做?
这是代码:
my @email;
my @gender;
my @state;
while ( <> ) {
chomp;
my @fields = split /,/;
push @gender, $fields[5];
push @email, $fields[3];
push @state, $fields[4];
}
#records
print "There are $_ records in this file\n" for scalar (@email-1);
print "\n";
#gender
my %count;
$count{$_}++ for @gender;
while( my ($gender => $count) = each %count) {
delete $count{gender};}
print "Male/Female distribution:\n";
print join(' ',%count), "\n";
print "\n";
#email
#states
my %scount;
$scount{$_}++ for @state;
while( my ($state => $scount) = each %scount){
delete $scount{state};}
print join(' ',%scount), "\n";
及其结果:
8 NC 292 OK 163 NY 901 VA 477 PA 195 NE 62 OH 711 WV 37 NM 10 MO 7 NH 77 MA 689 MN 431 TX 920 ME 81 NJ 673 RI 91 AL 230 KS 22 ND 31 FL 461 CT 305 CA 1262 IA 139 DE 33 CO 118 MI 378 IN 211 AR 163 IL 811 KY 11
例如,我希望NM 10
后面有一个新行。
答案 0 :(得分:3)
将print join(' ',%scount), "\n";
更改为:
my $n;
print map {$n++; $n % 10 ? "$_ $scount{$_} ":"$_ $scount{$_}\n"} keys %scount;
答案 1 :(得分:3)
可能更具可读性:
my @results = %count;
while (@results) {
print(join(" ", splice(@results, 10)), "\n");
}