in reply to Re: Re^2: Counting keys with defined or undefined elements in a hash (behaviour of values())
in thread Counting keys with defined or undefined elements in a hash

Yes, each does not create a list. On the other hand, it does copy the value (and create a new scalar for the key, because the keys in hashes are not full blown scalars).

Which one to use depends, though - if you're dealing with a DBM tied hash, you'd probably not want to use values.. or for some of the half-million-key monsters I'm dealing with at the moment.

Also, I tend to prefer each when I'm dealing with every pair stored in hash but in no particular order, because it reduces redundancy. I don't need to name the hash in question more than a single time.

Makeshifts last the longest.

  • Comment on Re^4: Counting keys with defined or undefined elements in a hash (behaviour of values())

Replies are listed 'Best First'.
Re: Re^4: Counting keys with defined or undefined elements in a hash (behaviour of values())
by Oberon (Monk) on Jun 07, 2003 at 02:18 UTC
    > Yes, each does not create a list. On the other hand, it does copy the value ...

    Hmmm ... so would it be fair to say that each does use less memory, even though it's slower?

    > ... (and create a new scalar for the key, because the keys in hashes are not full blown scalars).

    Well, actually, in my test script I was doing

    while (my (undef, $v) = each %fred)

    to avoid that one (at least I hope it avoids it!), but apparently copying the values was enough to make it 6x slower, which really surprised me.

      I think that just throws the created scalar away, but doesn't avoid its creation. The function is not only copying the values, it also has to keep track of its iterator, not to mention and requires a function call for every pair in the hash, rather than a single one for all of them. It does use less memory though, yes, that's what I meant when I said it's desirable when dealing with large hashes.

      Makeshifts last the longest.

        > I think that just throws the created scalar away, but doesn't avoid its creation.

        Well that's lame.

        > ... and requires a function call for every pair in the hash, rather than a single one for all of them.

        Right; I hadn't considered that.

        > It does use less memory though, yes, that's what I meant when I said it's desirable when dealing with large hashes.

        Ah, good, then I'm not completely insane. :-) I had switched from values to each on an ETL project last year, and I was remembering that I'd done it for speed reasons, but now that I think about it, it may very well have been for memory purposes instead.

        Thanx for the clarifications.