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

I always thought that using values created a new array (as opposed to using each, which didn't), but nobody mentioned it here, so I'm guessing I'm wrong. Is this something that used to be true but now isn't (and, if so, does anybody know as of what version), or am I just totally confoozled on this one?

I like the suggestion of a tied hash, but it could be problematic if it's possible for the values to change from undef to 1 (or vice versa).

  • Comment on Re: Counting keys with defined or undefined elements in a hash

Replies are listed 'Best First'.
Re^2: Counting keys with defined or undefined elements in a hash (behaviour of values())
by Aristotle (Chancellor) on Jun 07, 2003 at 00:52 UTC
    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.

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