
fashimpaur
User
Feb 20, 2002, 6:54 AM
Post #2 of 3
(57960 views)
|
Okay, as the forum states, today I give the answer and an explanation. The answer is: [perl] %colors = reverse %fruits; [/perl] The explanation is quite simple. The perl function 'reverse' expects one parameter, a LIST. If the method is invoked where the return result expected is another LIST, the value returned is a LIST in the opposite order. In this case, since a hash is passed and it is a named name/value pair list (as opposed to an anoymous LIST) and we are expecting a list context (determined by the left side of the equation), then an opposite ordered list is stored in the %colors hash. Because we said that the list we want to stuff our returned value into is a special name/value pair list, we can now use it's keys to get values returned. Note that I specified that each value in the first hash had to be unique. This is because when reverse occurs, had two values been the same, the following scenario would have occurred: Assume that we had added $fruits{lemon} = yellow to the hash. reverse would process the first (no telling if it would be banana or lemon) key 'yellow' the associated value 'lemon' (assuming that lemon was the first to process) Then, later, when 'yellow' comes up again, the method would see that there already was a key 'yellow' defined and would set it's value to 'banana'. At this point, lemon was lost. Hashes do not store the keys in any order. It is purely random. Had the first processed been 'banana', then $colors{yellow} would have the value 'lemon' and 'banana' would be lost. Then, you ask, why would you want to do this? Well, the time you want to do this is when you have a known hash than can only have unique values for the given keys. Then, when it is reversed, you can reference a given value to get it's key name. This might be useful for figuring out what field name to store data in a database after a form was submitted with only the value returned, (like from a menu list on a cgi form). Hope this was a useful note for you. If I have mistated anything, I would appreciate a private reply so that I may fix the error while this is editable. Dennis $a="c323745335d3221214b364d545". "a362532582521254c3640504c3729". "2f493759214b3635554c3040606a0", print unpack"u*",pack "h*",$a,"\n\n";
|