Reputation: 95
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?
#!/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;
Upvotes: 0
Views: 53
Reputation: 126742
All you need is
print join(' ', %count), "\n"
output
Female 4946 Male 5054 gender 1
Upvotes: 1
Reputation: 15411
You probably have a header line in your input file that contains gender
as a column title and that is read and counted once. 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
. The code block for map
will build the string for each pair:
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";
}
Upvotes: 0
Reputation: 241988
You are not printing an array, you are printing a hash. Use a loop to print it (you may hide it into a map
). Also, why do you populate the @gender array, when you can create the hash directly?
#!/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.
Upvotes: 2