Ah, no need to splice.
# @keys = keys %hash; # done ONCE
# ($k,$v) = rhe(%hash,@keys);
sub rhe (\%\@) {
my( $hv, $av )= @_;
my $idx= rand @$av;
my $key= $av->[$idx];
my $val= delete $hv->{$key};
my $last= pop @$av;
$av->[$idx]= $last if $idx < @$av;
return( $key, $val );
}
As for saving space, I don't see you really making use of the hash here so you could do:
@keys = keys %hash;
@vals = values %hash;
undef %hash;
If the keys are long, then you could also probably save a bit of space by storing reference to the keys in the array instead of the key values themself (or maybe not).
-
tye
(but my friends call me "Tye")