As has been suggested, you may want to consider a database. However, if all you have is a person's name, how do you ensure that the names are unique? If you have two names set to "Twinkletoes", you're going to have a problem.
Assuming that you have unique names, why not drop the id number? However, I wouldn't drop the it - a person may get married, change their name, have their real identity exposed, etc. But if you're not storing the names for long, it may not be relevant.
An id number is used to provide a non-identifying means of getting to the data that you want. One way to do this is to map the cities to an array (we assume you might have more than one city because you may have duplicate names):
my %people = ( 7 => { name => 'Bob Jones',
address => '555 Anywhere Street',
city => 'Allentown',
state => 'Pennsylvania' },
3 => { name => 'Pete Hollister',
address => '222 Northview Drive',
city => 'Shoreham',
state => 'unknown' },
9 => { name => 'Pete Hollister',
address => '222 Northview Drive',
city => 'New York',
state => 'unknown' }
);
my $name = 'Pete Hollister';
my @cities = map { $people{ $_ }{ name } eq $name ? $people{ $_ }{ cit
+y } : () } keys %people;
$,=', '; # This sets the array separator to a comma and space, allowin
+g
# easy printing of arrays
print @cities;
That should print "New York, Shoreham".
However, if names are guaranteed to be unique, use them as the hash key and just print $people{ $name }{ city }. This is really the only way you're going to avoid a loop unless you have the unique id number up front.
You're facing the problem that as your data grows more complex, your code usually must grow more complex with it. Take the information above and stuff it away into a subroutine, or better still, take Adam's suggestion and go with an object-oriented module. I'm guessing that you may not be familiar with the latter due to the nature of your question, but it's easier than you might suspect once you get used to the syntax and the new way of thinking.
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats. |