in reply to Re: Re: Stuck while learning about the hash
in thread Stuck while learning about the hash

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!

Replies are listed 'Best First'.
Re: Re: Re: Re: Stuck while learning about the hash
by Stamp_Guy (Monk) on Jun 08, 2001 at 08:21 UTC
    Mr. Nick:
    Thanks, that is exactly what I was looking for. I'm still just barely getting a handle on hashes now. If anyone is willing and able to explain how these hash calls are working, I would be quite interested! Thanks!
    Stamp_Guy