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!

In reply to Re: Re: Re: Stuck while learning about the hash by mr.nick
in thread Stuck while learning about the hash by Stamp_Guy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.