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!

Counting the matching terms of arrays within a Hash

Status
Not open for further replies.

sdslrn123

Technical User
Jan 17, 2006
78
GB
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:

Code:
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.
Code:
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);
@truth = split (',', $trainer[1]);
my %is_eaten_by = (
   $trainer[0]  => [ (@truth) ],
  );

foreach my $fruit (keys %is_eaten_by) {
   my $eaters = $is_eaten_by{$fruit};
   my $num_eaters = @$eaters;
   print("$num_eaters  ${fruit}: ",
         (@$eaters), "\n");
}
}

Ultimately I am looking to print:
Code:
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...

However, all I am getting is the number of terms within each array of the hash.

Thanks for any kind of help or advice
 
Try this:

open(DATA, "file.txt") or die "File could not be found $!";
while (<DATA>) {
chomp;
my @temp = split('=', $_);
my @nam = split(', ', $temp[1]);
foreach (@nam) {
$nam{$_}[0] .= ' ' . $temp[0];
$nam{$_}[1]++;
}
}


foreach (keys %nam) {
print $_ . ' can be found ' . $nam{$_}[1] . ': ' . $nam{$_}[0] . "\n";
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top