Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

How do I shuffle an array randomly?

by faq_monk (Initiate)
on Oct 08, 1999 at 00:20 UTC ( #615=perlfaq nodetype: print w/replies, xml ) Need Help??

Current Perl documentation can be found at

Here is our local, out-dated (pre-5.6) version:

Use this:

    # fisher_yates_shuffle( \@array ) : 
    # generate a random permutation of @array in place
    sub fisher_yates_shuffle {
        my $array = shift;
        my $i;
        for ($i = @$array; --$i; ) {
            my $j = int rand ($i+1);
            next if $i == $j;
            @$array[$i,$j] = @$array[$j,$i];

    fisher_yates_shuffle( \@array );    # permutes @array in place

You've probably seen shuffling algorithms that works using splice, randomly picking another element to swap the current element with:

    @new = ();
    @old = 1 .. 10;  # just a demo
    while (@old) {
        push(@new, splice(@old, rand @old, 1));

This is bad because splice is already O(N), and since you do it N times, you just invented a quadratic algorithm; that is, O(N**2). This does not scale, although Perl is so efficient that you probably won't notice this until you have rather largish arrays.

Log In?

What's my password?
Create A New User
[Corion]: ovedpo15: You could split on comma, and then join everything together, except the last part. Or you could match and make sure that the last part has no comma, like qr!,[^,]+$!, or you could use rindex.
[ovedpo15]: But I don't know the length of the string. will it still work?
[ovedpo15]: The only thing I know is that there is a comma at the end and a value after that
[hippo]: Try it and see. Your computer won't explode.
[Corion]: length will tell you the length of a string.
[Corion]: But if you are parsing CSV, again, let me point to Text::CSV_XS, which you should use instead
[hippo]: +1 for Text::CSV_XS
[ovedpo15]: Im not allowed to use additional modules, so I can't use it. looking for a simple regex to do this task though..

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (10)
As of 2018-05-27 10:39 GMT
Find Nodes?
    Voting Booth?