Re: How do I find the key of a specific hash element?

[email protected] (Joshua Hoblitt)
Newsgroups perl.beginners
Message-ID <[email protected]>
On Mon, May 19, 2008 at 06:51:17PM -0500, Wagner, David --- Senior Programmer Analyst --- WGO wrote:
> > -----Original Message-----
> > From: jshock [mailto:[email protected]] 
> > Sent: Monday, May 19, 2008 07:20
> > To: [email protected]
> > Subject: How do I find the key of a specific hash element?
> > 
> > For example:
> > 
> > my %weekdays = (
> > 	0  => "SUN",
> > 	1 => "MON",
> > 	2 => "TUE",
> > 	3 => "WED",
> > 	4 => "THU",
> > 	5 => "FRI",
> > 	6 => "SAT",
> > );
> > $weekdays{2}; # gives "TUE"
> > 
> > But what if I know "TUE" and want to find out what the key is? Is
> > there a construct like $weekdays{"TUE"} that gives 2"
> > 
> 	It depends on what information you will have and how big and how
> often will you need to access that data. You can either search the
> weekdays hash looking for the value or build a hash that has the the
> keys turned around(ie, the SAT is the key and 6 is the value.

At some point as hash size increases it will be faster to use a reverse lookup
hash than doing a linear search through a hash converted to a list (I haven't
benchmarked it but the turn over point is probably for hashes with only 1 or 2
digits worth of keys).  However, I would generally always use the reverse hash
as I think it's cleaner looking code. Eg.

my %rev_weekdays = map { $weekdays{$_} => $_ } %weekdays;
print $rev_weekdays{TUE};

Cheers,

-J

--
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.