Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: How do I select a random key from a hash?

by mirod (Canon)
on Feb 05, 2001 at 20:57 UTC ( [id://56433]=note: print w/replies, xml ) Need Help??


in reply to How do I select a random key from a hash?

The brute force solution:

/bin/perl -w use strict; my %h=( k1 => "v1", k2 => "v2", k3 => "v3"); my @keys= keys %h; my $k= $keys[int rand( @keys)]; print "random key: $k\n";'

If you want to do this on a huge hash and you want to do lots of random access and updates then you should look at Building a Better Hash, a pretty clever way to solve this problem.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://56433]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-03-28 13:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found