Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Little tricks

Get 'x' number of unique, random, elements from an array by KevinADC
Posted: 3 Feb 07 (Edited 15 Feb 07)

ignore this section:


Two ways (of many more I am sure) of returning "x" number of random yet unique elements from one array to a new list/array. First way uses the core module List::Util.


use List::Util qw/shuffle/;  
my @pop = (1..100);
my $samples = 30;
my @sample = (shuffle(@pop))[0..$samples-1];
print "@sample";

The shuffle() function randomly shuffles (mixes) the array. Then using an array slice [0..x] we take just the number of elements we want from the beginning of the shuffled array.      

The second way uses a hash to insure uniqueness and the rand() function to get random elements from the array.


my @pop = (1..100);
my $samples = 30;# see note below
my @sample = rand_sample(30,@pop);
print "@sample";
sub rand_sample {
   my ($n,@n) = (shift,@_);
   return 0 unless ($n < scalar @n);# see note below  
   my %seen = ();
   until (keys %seen == $samples) {
      $seen{$pop[rand @pop]}=1;
   return(keys %seen);

The "until" loop continues until we have the requested number of samples from the original array. Because hash keys must be unique, we get a list of unrepeated samples from the original array.

Note: this value must be less than the length of the array or the script will go into an infinte loop. It could be equal but then all you would be doing is shuffling the original array.



Back to Perl FAQ Index
Back to Perl Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close