Sunday, July 26, 2009

adventures in ignorance: each, keys, and values

So, each, keys, and values all use the same iterator under the covers. I knew this and it is the reason I almost never use each. There is just too much chance of each leaving the iterator partway through the hash. For instance, the following code is fine:

All of this means I only dust off each and try to remember all of its issues when I know the number of keys in the hash (or the size of the keys themselves) is going to be huge in relation to memory (which generally means it is a tied dbm). However, it just struck me today that this behavior has can be used for good. I want to loop over a bunch of hash entries checking to see if the are all equal to each other. Now I could say:

1 comment:

You can use each in scalar context – it will return just the key. No need for the throw-away $value declaration.

Also, keys in void context will reset the iterator without doing anything else; this is documented behaviour. Therefore you can safely use each in loops that won’t ever call any code that’s not under your control – eg. simple construction of a string from the data in a hash.