List::Util - List Utility
List::Util is a module that provides various operations on list or array.
# Load List::Util use List::Util; # When importing a function use List::Util 'max', 'min';
max function - maximum value
Use max to find the maximum value of an array element.
# Find the maximum value my @nums = (5, 3, 4); my $max = List::Util::max(@nums); # Five print "$max\n";
min function - minimum value
Use min to find the minimum value of an array element.
# Find the minimum value my @nums = (5, 3, 4); my $min = List::Util::min(@nums); # 3 print "$min\n";
sum function - sum
Use sum to sum the elements of the array.
# Find the total my @nums = (5, 3, 4); my $min = List::Util::sum(@nums); # 12 print "$min\n";
shuffle function - Randomly change the order of elements
Use shuffle to randomly change the order of the elements in the array.
# Randomly change the order of elements my @nums = (5, 3, 4, 7, 2, 9); my @nums_shuffle = List::Util::shuffle(@nums); # 2 5 7 3 9 4 (changes every time) print "@nums_shuffle\n";
first function - get the first element that matches the condition
Use first to get the first element that matches the condition. Each element of the array is passed to default variable "$_".
# Get the first match my @nums = (5, 3, 4, 9, 2, 7); my $match_first = List::Util::first {$_ > 5} @nums; # 9 print "$match_first\n";
Since the syntax is similar to the map function, please also refer to map function.
uniq function - get a unique set
To get a unique set, use the uniq function.
# Get a unique set my @nums = (5, 5, 5, 1, 3, 3); my @no_dup_nums = List::Util::uniq(@nums); # 5 1 3 print "@no_dup_nums\n";