Here's my 10-ct's worth. This is a bit after all the other posts, so it's probably not much help, (insert random excuse here about having to work next to my client) but I decided to post it anyways.

I got lazy and I also noticed that this is a question about learning to use hashes so I'm keeping the hash references down to a minimum and am using the key to point to useful data. However, doing this loses the sorting capabiltiy that a hash of hashes would allow, so it's sub-optimal.

#!/usr/bin/perl -w use strict; my %items; open(DB, "db.txt") || die "Could not open the database: $!"; while(<DB>) { chomp; my @record = split(/\t/); my $scottnum = shift @record; my @details = split(/\|/, shift @record); foreach my $detail (@details) { my @item = split(/,/, $detail); if ( ($item[0]) && ($item[1]) ){ $items{$scottnum.'-'.(shift @item)} = shift @item; } } } foreach my $key (sort (keys %items) ) { my ($sn,$mk) = split ('-',$key); print "key: $key \tmk: $mk\t sn: $sn item: $items{$key}\n"; }

The script returns:

key: 614-16.00 mk: 16.00 sn: 614 item: MNH key: 614-32.00 mk: 32.00 sn: 614 item: USED key: 614-50.00 mk: 50.00 sn: 614 item: PB key: 615-12.00 mk: 12.00 sn: 615 item: USED key: 615-36.00 mk: 36.00 sn: 615 item: MNH key: 615-50.00 mk: 50.00 sn: 615 item: PB key: 616-10.00 mk: 10.00 sn: 616 item: PB key: 616-2.00 mk: 2.00 sn: 616 item: USED key: 616-96.00 mk: 96.00 sn: 616 item: MNH

tested on solaris something or other.

I noticed in the original code that the printing statement was in the wrong place, which is most of why the output errors happened.

--hackmare.


In reply to Re: Re: Re: Stuck while learning about the hash by hackmare
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.