简体   繁体   English

如何格式化打印计数的输出

[英]How do you format the output of printing count

The following code gives the result of 以下代码给出了

Female4946Male5054gender1

How do I add spaces between the element and its number and why is it printing the array with a 1 next to it? 如何在元素及其编号之间添加空格,为什么在数组旁边打印1?

#!/usr/bin/perl

use strict;
use warnings;

my @gender;
my $female=0;

while (<>) {
    chomp;
    my @fields = split /,/;
    push @gender, $fields[5];
}

my %count;
$count{$_}++ for @gender;
print %count;

You are not printing an array, you are printing a hash. 您不是在打印数组,而是在打印哈希。 Use a loop to print it (you may hide it into a map ). 使用循环将其打印(您可以将其隐藏在map )。 Also, why do you populate the @gender array, when you can create the hash directly? 另外,当您可以直接创建哈希时,为什么还要填充@gender数组?

#!/usr/bin/perl
use strict;
use warnings;

my %count;

while (<>) {
    chomp;
    my @fields = split /,/;
    $count{ $fields[5] }++;
}

for my $gender (keys %count) {
    print $gender, ' ', $count{$gender}, "\n";
}

The 1 at the end comes from a line that hash gender in its sixth column (a header maybe?) You can delete $count{gender} before printing it, or add a <> before the while loop to skip the header. 末尾的1来自在其第六列中哈希gender的行(可能是标题吗?),您可以在打印delete $count{gender}之前将其delete $count{gender} ,或在while循环之前添加<>以跳过标题。

All you need is 所有你需要的是

print join(' ', %count), "\n"

output 输出

Female 4946 Male 5054 gender 1

You probably have a header line in your input file that contains gender as a column title and that is read and counted once. 您的输入文件中可能会有一个标题行,其中包含gender作为列标题,并且该行被读取并计数一次。 Skip the first line by reading a single line from the filehandle into void. 通过从文件句柄中将一行读取为空来跳过第一行。

<>;

To insert a space between every pair (but not after the last pair!) use join . 要在每对之间插入一个空格(但不要在最后一对之后插入!),请使用join The code block for map will build the string for each pair: map的代码块将为每对构建字符串:

print join " ", map {"$_: " . $count{$_} } keys %count;
print "\n";

Or more nicely (from my point of view) with newlines between them: 或更妙的是(从我的角度来看),它们之间有换行符:

while( my ($gender => $count) = each %count) {
    print "$gender: $count\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM