in reply to Random hash element (low memory edition).

The order in which keys are returned by keys/each/value are supposed to be random (not crypotgraphically random, but explicity coded as random, with the random factor being different for each run (see PERL_HASH_SEED).

So why not just grab the first element of the hash? Or if you need more than one, grab the first N? Or you need a single random element from time to time, either maintain a counter and grab element $n++ using the methods discussed eaither in this thread, or if you can guarantee that the hash's iterator won't be used elsewhere, you can use 'each' to get the next element.

Dave.

  • Comment on Re: Random hash element (low memory edition).

Replies are listed 'Best First'.
Re^2: Random hash element (low memory edition).
by moritz (Cardinal) on Jan 24, 2008 at 23:11 UTC
    The order in which keys are returned by keys/each/value are supposed to be random (not crypotgraphically random, but explicity coded as random, with the random factor being different for each run (see PERL_HASH_SEED).

    If they are, then my perl is quite buggy.

    I ran perl -MData::Dumper -we 'print Dumper \%ENV' a few times, both with perl 5.8.8 and 5.10.0 (on Debian Etch i386), and I always got the same order.

    (And this is no Data::Dumper artifact - it works with join ", ", keys %ENV as well.)

    It is true that you shouldn't rely on a particular hash order, but it doesn't mean a randomized order is guaranteed.

      My mistake. The first cut of the hash randomisation code always randomised, but then it was changed to only randomise in pathological cases, to avoid too much code breakage.

      Dave.

Re^2: Random hash element (low memory edition).
by bart (Canon) on Jan 27, 2008 at 12:39 UTC
    The order in which keys are returned by keys/each/value are supposed to be random (not crypotgraphically random, but explicity coded as random, with the random factor being different for each run (see PERL_HASH_SEED).
    Uh, it may be different each time you run the script, but if you iterate through the same hash twice in your script, you'll get the same order twice.