Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Answer: How do I shuffle an array?

by hossman (Prior)
on Jun 15, 2003 at 22:50 UTC ( #266082=categorized answer: print w/replies, xml ) Need Help??

Q&A > arrays > How do I shuffle an array? - Answer contributed by hossman

The List::Util module provides a shuffle function which implements the Fisher-Yates shuffle.
use List::Util qw(shuffle); my @data = (0..51); my @cards = shuffle @data;

Replies are listed 'Best First'.
Re: Answer: How do I shuffle an array?
by wufnik (Friar) on Jun 16, 2003 at 11:01 UTC
    I prefer japhy's one-liner, which achieves shuffling via fisher-yates:

    @entry[-$i,$j] = @entry[$j,-$i] while $j = rand(@entry - $i), ++$i < @ +entry;
    as an aside - this is in the snippets section. would it not be nice to use snippets, or grinder's fabled categorized snippets library, as a source of data for categorized q&a?



    -- in the world of the mules there are no rules --
Re: Answer: How do I shuffle an array?
by gmpassos (Priest) on Jun 16, 2003 at 03:31 UTC
    Independet way:
    my @data = 0..51; my @cards = sort { (-1,1)[rand(2)] } @data ;

    Graciliano M. P.
    "The creativity is the expression of the liberty".

Re: Answer: How do I shuffle an array?
by jdhedden (Deacon) on Dec 05, 2006 at 17:05 UTC
    Math::Random::MT::Auto has a shuffle function, as well:
    use Math::Random::MT::Auto 'shuffle'; my @cards = 0..51; shuffle(\@cards);

    Remember: There's always one more bug.
Log In?

What's my password?
Create A New User
[thao4]: thao4
[hippo]: Indeed you are.
[thao4]: Hi all, I am new in perl. I need do somthing in perl: exemple: - search a patern "CADRE 1.1 CPU" in one file.txt - incremente +30 lines from the line with the patern found - replace the patern "Model Regle" by "Heath Rule A" in this new line (30 line
[marto]: good morning all
[hippo]: Welcome. Tell me, have you read perlintro? That's a great place to start.

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (10)
As of 2018-02-21 09:42 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (276 votes). Check out past polls.