Perl Hash Count

时间:2014-04-28 16:03:23

标签: 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/){
$boycount=1;
$girlcount=0;
   }

if ($2 =~ /girl/){
$boycount=0;
$girlcount=1;
  }

接下来的部分是,如果该人在哈希中已经存在,则添加该人,然后为男孩和女孩开始计数。 (我认为这是正确的方法,不确定)

if (!$hash{$person}){
         %hash = (
            '$person' => [
                {'boy' => "0+$boycount", 'girl' => "0+$girlcount"}
            ],
            );

现在,我不知道如果人员已经存在于哈希中,如何继续更新哈希值内的值。

%hash = (
        '$person' => [
                {'boys' => $boyscount, 'girls' => $girlscount}
                ],
        );

我不知道如何继续更新哈希。

2 个答案:

答案 0 :(得分:3)

您只需要学习Perl Data Structures Cookbook

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

答案 1 :(得分:1)

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};
}