in reply to Re: Counting Data in two columns?
in thread Counting Data in two columns?

Basically my data is subject to change but will follow a format as follows where I will have a unique "Family Name" followed by "--" followed by various "family members". The contents of the data are unknown to me apart from the format: Data is a text file as follows:
FLINTSTONES -- BARNEY, FRED, WILMA JETSONS -- MAX, TONY, WILMA SIMPSONS -- LISA, BARNEY, WILMA, HOMER ALCATRAZ -- ELIJAH, MAX, WILMA
I know I can grab this into an array called @Dopli. And split each line $unix at "--" into an array @trainer Is there a way of pushing each array into a hash using $trainer[0] and $trainer1.
sub nice_list { return '' if @_ == 0; return shift if @_ == 1; my $last = pop; return join(', ', @_) . " and $last"; } my $unix; my @dopli; my @trainer; foreach $unix (@dopli){ @trainer = split ('=', $unix); my %is_eaten_by = ( $trainer[0] => [ qw($trainer[1]) ], ); foreach my $fruit (keys %is_eaten_by) { my $eaters = $is_eaten_by{$fruit}; my $num_eaters = @$eaters; my $s = $num_eaters == 1 ? 's' : ''; my $p = $num_eaters == 1 ? '' : 's'; print("$num_eaters person$p eat$s ${fruit}s: ", nice_list(@$eaters), "\n"); } }
Ultimately I am looking to print:
BARNEY can be found 2: FLINTSTONES SIMPSONS FRED can be found 1: FLINTSTONES WILMA can be found 4: FLINTSTONES JETSONS SIMPSONS ALCATRAZ MAX can be found 2: JETSONS ALCATRAZ and so forth...
Thanks for any kind of help or advice

Replies are listed 'Best First'.
Re^3: Counting Data in two columns?
by ikegami (Patriarch) on Jun 21, 2006 at 15:29 UTC

    The easiest way is to convert

    FLINTSTONES -- BARNEY, FRED, WILMA JETSONS -- MAX, TONY, WILMA SIMPSONS -- LISA, BARNEY, WILMA, HOMER ALCATRAZ -- ELIJAH, MAX, WILMA

    to

    my %is_in_show = ( MAX => [ 'JETSONS', 'ALCATRAZ' ], WILMA => [ 'FLINTSTONES', 'JETSONS', 'SIMPSONS', 'ALCATRAZ' ], HOMER => [ 'SIMPSONS' ], ELIJAH => [ 'ALCATRAZ' ], ... );

    when you read the file. The following accomplishes this:

    while (<FILE>) { chomp; my ($show, $names) = split(/ -- /); my @names = split(/, /, $names); foreach my $name (@names) { push(@{$is_in_show{$name}}, $show); } }