in reply to Re: Counting keys with defined or undefined elements in a hash
in thread Counting keys with defined or undefined elements in a hash

It does create a new list, but aliases the scalars rather than copy them. Observe:
#!/usr/bin/perl -lw use strict; my %foo = (0 => 0, 1 => 1, 2 => 2); $_++ for values %foo; print "$_ => $foo{$_}" for sort keys %foo;

Makeshifts last the longest.

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

Replies are listed 'Best First'.
Re: Re^2: Counting keys with defined or undefined elements in a hash (behaviour of values())
by Oberon (Monk) on Jun 07, 2003 at 01:56 UTC
    > It does create a new list, but aliases the scalars rather than copy them.

    Right, but I thought that using each didn't create a new list. But slapping a quick Benchmark together I see that keys is nearly 3x faster than each, and values is more than twice as fast as keys ... that totally blows my understanding of the process. And here I've been favoring each over keys or values on the grounds that it used less memory and was faster ... man have I been wrong!

      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.

        > 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.