You're getting the repeat because the %items hash isn't unique for each of the "$scottnum". You can fix it easily by putting an undef %items after you print out the hash.
if (($item[0] ne "") && ($item[1] ne "")){
$items{"$item[0]"} = "$item[1]";
foreach my $key (keys %items) {
print "$scottnum\t $key \t $items{$key}\n";
}
undef %items;
}
But this probably isn't what you wanted. You probably wanted a hash with a key and a subkey (a hash of hashes). I'm not good at explaining so let me show you instead:
while(<DB>) {
chomp;
@record = split(/\t/);
$scottnum = $record[0];
@details = split(/\|/, "$record[1]");
foreach $detail (@details) {
@item = split(/,/, "$detail");
if (($item[0] ne "") && ($item[1] ne "")){
###########################################
$items{$scottnum}{"$item[0]"} = "$item[1]";
###########################################
}
}
}
foreach my $scottnum (keys %items) {
for my $key (keys %{$items{$scottnum}}) {
print "$scottnum\t $key \t $items{$scottnum}{$key}\n";
}
}
This way a hash of hashes is created.
Stylistically, I would have probably done it something like:
my %info;
open(DB, "db.txt") || die "Could not open the database: $!";
while (<DB>) {
my @info=split /[\s|,]+/,$_;
my $scott=shift @info;
while (my $key=shift @info) {
$info{$scott}{$key}=shift @info;
}
}
close DB;
But you are definately on the right track!
|