What's That Noise?! [Ian Kallen's Weblog]

Main | Next day (May 1, 2004) »

20040430 Friday April 30, 2004

Randomizing a list Needing to to randomize the contents of a Perl array, I was just about to write the code myself but decided to snoop around CPAN first. Lo and behold, I found that there was something in the Perl distribution already that did what I need.

As of Perl 5.8, there's a module in the standard library with a boat load of things you need to with a list from time to time. It was nice to stumble upon the List::Util class; it's got a method called shuffle that does the trick. Here's an example of getting a randomized list using shuffle:

use List::Util 'shuffle';

my @list = ('a'..'z');
my @shuffled = shuffle(@list); 
# @shuffled is randomized, @list is unchanged
print "@shuffled\n";

There are more useful methods like min, max and sum that should make dealing with aggregations of values much easier. ( Apr 30 2004, 11:45:45 PM PDT ) Permalink