Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculating Percentages in a Hash?

Status
Not open for further replies.

sdslrn123

Technical User
Jan 17, 2006
78
GB
Is there a way to calculate the total number of terms altogether within arrays of a hash. I know I have to divide the following scalar but I can't figure out how to group the total number of "family members" in all the "families" of the hash.

Code:
print "$member can be found " . scalar(@{$family{$member}}) / [b]?[/b] . ": "

Code so far...

Code:
#!/usr/bin/perl
use Data::Dumper;
$Data::Dumper::Indent = 1; 

while(<DATA>) {
    chop;
    my($familyname,$memberstring) = split /\=/,$_;
    my @members = split /, /,$memberstring;
    foreach my $member(@members) {
        push(@{$family{$member}},$familyname);
    } 
} 
print Dumper(\%family); 
# show the data structure in %family
# now output a list of members with their families
foreach my $member(sort keys %family) {
    print "$member can be found " . scalar(@{$family{$member}}) . ": "
        . join(" ", @{$family{$member}}) . "\n";
}

Data:
Code:
FLINTSTONES=BARNEY, FRED, WILMA
JETSONS=MAX, TONY, WILMA
SIMPSONS=LISA, BARNEY, WILMA, HOMER
ALCATRAZ=ELIJAH, MAX, WILMA
Ultimately I am looking to print:
Code:
BARNEY can be found 2: FLINTSTONES SIMPSONS
BARNEY IS FOUND IN (2/Total)% of families

FRED can be found 1: FLINTSTONES
FRED IS FOUND IN (1/Total)% of families
e.t.c

Thanks for any kind of help or advice.
 
Did we ever resolve if this is homework or not?
I am still suspicious.
I hope it's not, because if it is you'll only be cheating yourself.
Anyway, try this:
Code:
#!/usr/bin/perl -w
use strict;

my %people   = ();
my %families = ();
while(<DATA>) {
    chomp;
    my ($family, $people) = split /=/, $_, 2;
    my @members           = split /,\s*/, $people, -1;
    foreach my $member (@members) {
        push @{$people{$member}}, $family;
        $families{$family}++;
    }
}
my $total_families = scalar(keys %families);
foreach my $name (sort keys %people) {
    print $name, " can be found ", scalar(@{$people{$name}});
    print ": @{$people{$name}}\n";
    print $name, " IS FOUND IN ", (scalar(@{$people{$name}})/$total_families *100), "% of families\n\n";
}

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


Trojan.
 
Thanks. I do try and take on your advice to problem solve myself otherwise I am only cheating myself. Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top