Domanda

I have a table with users the gender of their kids in seprate lines.

lilly boy
lilly boy
jane girl
lilly girl
jane boy

I wrote a script to put parse the lines and give me a total at the end

lilly boys=2 girls1
jane  boys=1 girls=1

I tried this with a hash, but I dont know how to approach it

foreach $lines (@all_lines){

if ($lines =~ /(.+?)/s(.+)/){
$person = $1;
if ($2 =~ /boy/){
$boycount=1;
$girlcount=0;
   }

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

the next part is, if the person doesn't already exist inside the hash, add the person and then start a count for boy and girl. (i think this is the correct way, not sure)

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

Now, I dont know how to keep updating the values inside the hash, if the person already exists in the hash.

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

I am not sure how to keep updating the hash.

È stato utile?

Soluzione

You just need to study the 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

Altri suggerimenti

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};
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top