How to shuffle a list in Perl

| 1 Comment

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 qw( shuffle );
my @files = glob( '*' );
@files = grep { -f } @files;
@files = shuffle @files;

Of course you can combine that into one expression:

use List::Util qw( shuffle );
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

The shuffle function is extremely simple, and how here's a little article that explains why it works.

1 Comment

You left out the qw/shuffle/ in your examples (except for the commandline version).

Leave a comment

Job hunting for programmers

Land the Tech Job You Love, Andy Lester's guide to job hunting for programmers and other technical professionals, is available in PDF, ePub and .mobi formats, all DRM-free, as well as good old-fashioned paper.