In Perl, you can shuffle an array using the shuffle
function provided by the List::Util module, which implements the Fisher-Yates shuffle algorithm.
In this example,
@int_array
containing integers.shuffle
function from List::Util to shuffle @int_array
.use List::Util qw(shuffle);
my @int_array = (1, 2, 3, 4, 5);
my @shuffled_array = shuffle(@int_array);
print 'Shuffled Array:', join(' ', @shuffled_array);
Shuffled Array: 4 1 2 5 3
In this example,
@str_array
containing strings.shuffle
function from List::Util to shuffle @str_array
.use List::Util qw(shuffle);
my @str_array = ('apple', 'banana', 'cherry');
my @shuffled_array = shuffle(@str_array);
print 'Shuffled Array:', join(' ', @shuffled_array);
Shuffled Array: banana apple cherry
In this tutorial, we learned How to Shuffle an Array in Perl language with well detailed examples.