in reply to Re: trouble with each and a hash of hashes
in thread trouble with each and a hash of hashes

Thanks a lot!

Following the advice given to me by y'all and doing some more debugging I found out the problem:

Once I find what I want during the "while ..(..each)" loop, I exit the loop.

The next time, "each" starts from the pair in the list after the one where I stopped the previous time.

If I exit the loop during the iteration in which "each" returned the very last pair in the list, the next time the loop is not even entered.

So, I will go for a foreach loop instead.

Well, thanks again -- now it looks obvious but I would have never been able to find out by myself!

Marco
  • Comment on Re: trouble with each and a hash of hashes

Replies are listed 'Best First'.
Re^2: trouble with each and a hash of hashes
by BrowserUk (Patriarch) on Sep 11, 2004 at 22:45 UTC
    So, I will go for a foreach loop instead.

    As a solution, that will work fine--but it's not without it's downside.

    Using while each, avoids a (possibly significant) overhead that for keys or for values impose: that of constructing a list. If your hash is small, and if your going to iterate most of the elements anyway, then that may be acceptable.

    However, there is a better way: If you call keys on the hash(ref) before entering your while loop, it will reset the iterator and you will avoid the problems you detailed above. keys is specifically optimised for this purpose. From perlfunc:

    As a side effect, calling keys() resets the HASH's internal iterator, see each. (In particular, calling keys() in void context resets the iterator with no other overhead.)

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon