| #!/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: |
| #============================================================ |