Perl哈希计数
我有一张表格,上面有用户的孩子的性别Perl哈希计数,perl,hash,count,key,Perl,Hash,Count,Key,我有一张表格,上面有用户的孩子的性别 lilly boy lilly boy jane girl lilly girl jane boy 我写了一个脚本来分析这些行,并在最后给出一个总数 lilly boys=2 girls1 jane boys=1 girls=1 我尝试了一个杂凑,但我不知道如何处理它 foreach $lines (@all_lines){ if ($lines =~ /(.+?)/s(.+)/){ $person = $1; if ($2 =~ /boy/){ $
lilly boy
lilly boy
jane girl
lilly girl
jane boy
我写了一个脚本来分析这些行,并在最后给出一个总数
lilly boys=2 girls1
jane boys=1 girls=1
我尝试了一个杂凑,但我不知道如何处理它
foreach $lines (@all_lines){
if ($lines =~ /(.+?)/s(.+)/){
$person = $1;
if ($2 =~ /boy/){
$boycount=1;
$girlcount=0;
}
if ($2 =~ /girl/){
$boycount=0;
$girlcount=1;
}
下一部分是,如果散列中还没有这个人,那么添加这个人,然后开始对男孩和女孩进行计数。(我认为这是正确的方法,不确定)
现在,如果散列中已经存在这个人,我不知道如何不断更新散列中的值
%hash = (
'$person' => [
{'boys' => $boyscount, 'girls' => $girlscount}
],
);
我不知道如何不断更新哈希值。您只需要研究
使用严格;
使用警告;
我的%人;
而(){
咀嚼;
我的($父母,$性别)=分裂;
$person{$parent}{$gender}++;
}
使用数据::转储;
dd\%人;
__资料__
莉莉男孩
莉莉男孩
简女孩
莉莉女孩
简男孩
您只需研究
使用严格;
使用警告;
我的%人;
而(){
咀嚼;
我的($父母,$性别)=分裂;
$person{$parent}{$gender}++;
}
使用数据::转储;
dd\%人;
__资料__
莉莉男孩
莉莉男孩
简女孩
莉莉女孩
简男孩
严格使用;
使用警告;
我的%hash;
打开我的$fh,“使用strict;
使用警告;
我的%hash;
打开我的$fh,'非常感谢。这很简单,比我想象的要简单得多。谢谢你的详细解释,非常感谢。这很简单,比我想象的要简单得多。谢谢你的详细解释,很好。
%hash = (
'$person' => [
{'boys' => $boyscount, 'girls' => $girlscount}
],
);
use strict;
use warnings;
my %person;
while (<DATA>) {
chomp;
my ($parent, $gender) = split;
$person{$parent}{$gender}++;
}
use Data::Dump;
dd \%person;
__DATA__
lilly boy
lilly boy
jane girl
lilly girl
jane boy
use strict;
use warnings;
my %hash;
open my $fh, '<', 'table.txt' or die "Unable to open table: $!";
# Aggregate stats:
while ( my $line = <$fh> ) { # Loop over record by record
chomp $line; # Remove trailing newlines
# split is a better tool than regexes to get the necessary data
my ( $parent, $kid_gender ) = split /\s+/, $line;
$hash{$parent}{$kid_gender}++; # Increment by one
# Take advantage of auto-vivification
}
# Print stats:
for my $parent ( keys %hash ) {
printf "%s boys=%d girls = %d\n",
$parent, $hash{$parent}{boy}, $hash{$parent}{girl};
}