This worked well until I wanted to look up someone's address by Name instead of category. So I wrote a subroutine to do that... but there went the efficiency of a hash! So now I'm wondering if anyone can think of a more efficient way to do this (keeping in mind that there are only about 15 names and 4 or 5 categories... so far.)
I suspect that I might just redo the hash to be less complex, maybe make names and categories keys, but have categories return an array of names... making the user have to re-access the hash with each name if a list gets returned... hmmm thats almost as ugly.my %EMail = ( # This hash best accessed via GetEMailFor() Category1 => { "Name One", 'some1@address.com', }, Category2 => { "Name Two", 'some2@address.com', "Name Three", 'some3@address.com', }, Category3 => { "Name Four", 'some4@address.com', "Name Five", 'some5@address.com', "Name Six", 'some6@address.com', "Name Seven", 'some7@address.com', "Name Eight", 'some8@address.com', }, # And so on... ); # GetEMailFor( $key, [$key2, $key3...] ) # # Returns the requested e-mail address. # If more then one address is found, they are returned as # a comma delimeted scalar. # The $key may be the person's category or name. # sub GetEMailFor { my @addresses = (); while( @_ ) { my $request = shift; for( keys %EMail ) { if( $_ eq $request ) { push @addresses, values %{$EMail{$_}}; next; } for my $name ( keys %{$EMail{$_}} ) { if( $name eq $request ) { push @addresses, ${$EMail{$_}}{$name}; next; } } } } return join ',', reverse @addresses if $#addresses; return $addresses[0]; } # So print GetEMailFor( 'Category2' ); # prints: some2@address.com,some3@address.com print GetEMailFor( 'Name Five' ); # prints: some5@address.com print GetEMailFor( 'Category1', 'Name Seven' ) # prints: some1@address.com,some7@address.com
In reply to Complex Hash by Adam
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |