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: beginners@perl.org > > 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 -- -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/