Saturday, November 24, 2007

Perl : selecting randomly elements of an array

#!/usr/bin/env perl
use strict;
my @test = (0,1,2,3,4,5);
my $i = 6;
while($i > 0){
       my $offset = int(rand(scalar(@test)+1)) - 1;
       print $test[$offset]."\n";
       splice(@test,$offset,1);
       $i--;
}

2 comments:

Anonymous said...

my $i = 6;
may be replaced by
my $i = scalar(@test);

Ketan said...

Oh yes ! Thank you for the correction/improvement.

Ketan