This post originated from an RSS feed registered with Perl Buzz
by Andy Lester.
Original Post: How to shuffle a list in Perl
Feed Title: Perlbuzz
Feed URL: http://perlbuzz.com/atom.xml
Feed Description: What's happening in the world of Perl programming, including Perl 5, Perl 6, the CPAN and Parrot?
If you've got a list of things in Perl, and you want them in random order, don't try to make up a way to do it yourself. Use the shuffle function in the List::Util module. Say you want a list of files from a directory:
use List::Util;
my @files = glob( '*' );
@files = grep { -f } @files;
@files = shuffle @files;
Of course you can combine that into one expression:
use List::Util;
my @files = shuffle grep { -f } glob( '*' );
Or from the command line:
perl -MList::Util=shuffle -le'print for shuffle grep {-f} glob("*")'
Don't worry that List::Util is a module, because it's a core module that's been included with Perl since 5.7.3
$ corelist List::Util
List::Util was first released with perl 5.007003