How about this:
#!/usr/bin/perl my $myfile = 'somefile'; my %by_id = (); my %by_name = (); open (IN, '<', $myfile) or die "Can't open $myfile: $!\n"; sub ID () {0} sub NAME () {1} sub STREET () {2} sub CITY () {3} sub ZIP () {4} sub PHONE () {5} sub START_DT () {6} while (<IN>) { my @f = split /\|/o; $by_id{$f[ID]} = \@f; $by_name{$f[NAME]} = \@f; # etc for other indexes you want } my $id = 'fred'; if (exists $by_id{$id}) { print "$id's Address is ", $by_id{$id}->[ADDRESS], "\n"; } else { print "I've never heard of this $id guy.\n"; }
The idea is pretty simple: create a hash of references to arrays. Use inline functions to address the contents of the arrays (makes things more readable). If you want multiple indexes then you'd be better off using an database instead of trying to do it all in perl, but you could create a hash for each index and have them all point to the same array. I've done two, id and name, for example. Of course if your values aren't unique then you're indexes will get clobbered. Like I said, use a real database if you want to do database stuff. :)

Advanced Perl Programming has an excellent section on datastructures in Perl, which you might want to check out. Drew


In reply to Re: How to use hashes well by agh
in thread How to use hashes well by cosmicsoup

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.