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

You could use something like this:

Code updated per ikegami's post below.

sub getRandomPairFromHash{ my $href = shift; my $nKeys = keys %$href; my $n = 1 + int rand $nKeys; my( $key, $val ); ( $key, $val ) = each %$href while $n--; return ( $key, $val ) }

It does work and doesn't increase the memory consumption, but fast it's not.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^2: Random hash element (low memory edition).
by ikegami (Patriarch) on Jan 25, 2008 at 02:13 UTC

    That fails when $n == 0 and when $n == 1. One way to fix it is to apply both of the following changes:

    Change
    while --$n
    to
    while $n--

    Change
    my $n = int rand $nKeys;
    to
    my $n = 1 + int rand $nKeys;

    Update: Might as well post the modified code:

    sub getRandomPairFromHash{ my $href = shift; my $nKeys = keys %$href or return ( undef, undef ); my $n = 1 + int rand $nKeys; my( $key, $val ); ( $key, $val ) = each %$href while $n--; return ( $key, $val ) }