📘 How to randomise an array in Perl 6

📘 How to randomise an array in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


Shuffle the elements of an array in random order.

Arrays in Perl 6 have the pick method, which does the work.

my @a = 1..20;
say@a.pick(@a);

A possible output of the program looks like this:

(4 18 10 15 14 8 2 11 3 12 1 6 9 19 13 7 16 17 20 5)

The pick method expects an integer argument that defines the number of picked elements. In the example above, passing the array as an argument causes Perl to coerce it into an integer by calling the @a.Int method, which returns the length of the array.

After the operation, the original data remains unchanged. If you need to update the @a variable, use the .= operator to call a method and assign its result to the invocant:

@a.=pick(@a);

Elements of the array are not repeated in the output.

In Perl 6, arrays also have the roll method, which works similar but does not guarantee that the elements are not repeated.

say @a.roll(@a);

Calling either pickor rollwith no argument returns a single element from an array. If the value of the argument is bigger than the length of the array, the pick method returns the list of the same size as the original one, while roll happily generates more repeated items.

One thought on “📘 How to randomise an array in Perl 6”

  1. Pro-Tip: It’s probably worth mentioning… If you want to shuffle an arbitrary list —i.e.,  where you don’t know the number of elements in advance, and you don’t want to save it to an array — you can use:

    pick(Inf)

    For example:

    for $*IN.lines.pick(Inf) -> $line {
    # Do something...
    say $line if $line ~~ /^/;
    }

    or…

    .say for $*IN.lines
    ==> grep / ^ /
    ==> pick ∞; # For the Unicode-inclined

    [N.B.: Note that the first version shuffles then greps, whereas the second version greps first, then shuffles.]

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code