in reply to How to use hashes well
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. :)#!/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"; }
Advanced Perl Programming has an excellent section on datastructures in Perl, which you might want to check out. Drew
|
|---|