The Artima Developer Community
Sponsored Link

Perl Buzz Forum
How to shuffle a list in Perl

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Andy Lester

Posts: 518
Nickname: petdance
Registered: Jun, 2009

Andy Lester is an author and programmer.
How to shuffle a list in Perl Posted: May 28, 2010 8:42 AM
Reply to this message Reply

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?
Latest Perl Buzz Posts
Latest Perl Buzz Posts by Andy Lester
Latest Posts From Perlbuzz

Advertisement

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

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

Read: How to shuffle a list in Perl

Topic: Perlbuzz news roundup for 2010-05-28 Previous Topic   Next Topic Topic: To InformationWeek re: static code analysis

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use