How to get a random element from an array in Perl

Task. In the program in the programming language Perl has an array with the values. You need to get a random element from this array.

The solution to this problem in Perl looks very beautiful and elegant. Use the rand()function to produce a random index element.

Here is a sample code. There is an array which is in this array with the colors. The code displays a random color from the array.

▶ Run
#!/usr/bin/perl

my @colors = ('red', 'green', 'blue', 'magenta', 'white');

my $color = $colors[ rand @colors ];

print $color;

How it works. There is an array of @colors. It has 5elements. In order to address the first element you need to write $colors[0], to the last — $colors[4].

In this example, rand @colors is like rand(5). In this using an array it returns the number of elements in the array. (scalar context).

rand @colors returns a number from 0 (inclusive) to the number 5 (but not including this number). For example, the result of this operation can be number 3.70744988833152.

And the last step. The result rand @colors is used as the index array. Ie it turns out something like $colors[ 3.70744988833152 ]. This the entry returns the same array element as the entry $colors[3], i.e. the fourth element of the string 'magenta'.

Related topics

Other articles