Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: easy way to get random key from hash?

by eduardo (Curate)
on Aug 05, 2002 at 18:54 UTC ( #187775=note: print w/replies, xml ) Need Help??


in reply to easy way to get random key from hash?

This is ugly, but it seems to "work":
#!/usr/bin/perl -w use strict; my %hash = (foo=>1, bar=>2, baz=>3); print $hash{[keys %hash]->[int rand keys %hash]};
However, it still creates the "temporary array", it just makes it anonymous, inline, and therefore impossible to reuse (so, you go through all that trouble for no really good reason.) If you plan to, in your code, retrieve random keys more than once, I suggest just keeping the array around to save the cost of recreation. That is, until one of the more perl-gifted monks gives you a better answer than this :)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://187775]
help
Chatterbox?
[LanX]: yep
[erix]: or Ctrl-U to view current html :P
[LanX]: name not id
[LanX]: id isn't approved AFAIK
[LanX]: name works
erix feels silly for having actually tested that contiguous values make no difference in CLUSTERing a table (At least, in postges)
[LanX]: Perl Monks Approved HTML tags
[LanX]: erix and his postguess ...
[erix]: (Grrres...)
[dabella12]: I have a problem install tK on CeontOs using perl 5.24

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (9)
As of 2017-06-24 13:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many monitors do you use while coding?















    Results (557 votes). Check out past polls.