1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/perl -w
 
#############################################################
#============================================================
#=== Created By: Scott Thompson
#=== Created: 27th May 2009
#=== Version: 1.00.00
#=== Last Updated: 27th May 2009
#=== Copyright: (c) 2009, Scott Thompson, All Rights Reserved
#=== License: GNU
#=== Website: coderprofile.com/coder/VBAssassin
#============================================================
#############################################################
 
#============================================================
#=== Randomly pick an element out of an array, returns what was picked and removes the picked element from referenced array
#============================================================
sub random_pick {
       
       #how many items in the list are we looking at
       my $length = @{$_[0]};
       
       #get a random key from the list
       my $random = int(rand($length));
       
       #pick the element and delete the key
       my $picked = @{$_[0]}[$random];
       delete @{$_[0]}[$random];
       
       #resort the array
       my @cleaned_array = ();
       #--- for ($a=0; $a<$length; $a++) { - WRONG - USE A FOREACH(RANGE)
       foreach $key (0..$length) {
              if (defined(@{$_[0]}[$key])) {
                     push @cleaned_array, @{$_[0]}[$key];
              }
       }
       
       #send the new resorted array back to the referenced variable
       @{$_[0]} = @cleaned_array;
       
       #return what was picked and removed from the original array
       return $picked;
       
}
 
#============================================================
#=== EXAMPLE: Of how to use the function above
#============================================================
@data = qw[ scott matt tom ben sam ];
print "Picked: " . &random_pick(\@data) . "\n";
print "Remaining: @data\n";
print "Picked: " . &random_pick(\@data) . "\n";
print "Remaining: @data\n";
print "Picked: " . &random_pick(\@data) . "\n";
print "Remaining: @data\n";
print "Picked: " . &random_pick(\@data) . "\n";
print "Remaining: @data\n";
print "Picked: " . &random_pick(\@data) . "\n";
print "Remaining: @data\n";
 
#=== WILL PRINT SOMETHING LIKE...
# Picked: scott
# Remaining: matt tom ben sam
# Picked: tom
# Remaining: matt ben sam
# Picked: sam
# Remaining: matt ben
# Picked: ben
# Remaining: matt
# Picked: matt
# Remaining: 
#============================================================