arrange the elements of an array in random order
( categories: array )Use 'shuffle()' from List::Util module.
Example:
#!/usr/bin/perl
use List::Util qw(shuffle);
@sorted_array = (1, 2, 3, 4, 5, 6);
@random_array = shuffle(@sorted_array);
print '@random_array: ' . join(', ', @random_array) . "\n";
adding and removing elements in an array
( categories: array )- ADD A LIST OF ELEMENTS TO THE FRONT
unshift @array, @list;
NOTES:
- unshift returns the new number of elements in the array.
- @list is prepended as a whole; not one element at a time, so it does not behave exactly as a normal "push" operation in a stack.
- REMOVE THE FIRST ELEMENT
shift @array;
NOTES:
- shift returns the value of the discarded element
- if shift is applied on an empty array, it returns undef
- ADD A LIST OF ELEMENTS AT THE END
push @array, @list;
NOTE:
- push returns the new number of elements in the array
sort an array of numbers
( categories: array )By default the sort function uses alphabetical order to sort elements. To sort using numerical order, you have to use the syntax shown below.
- In ascending order:
@sorted_array = sort { $a <=> $b } @array;
- In descending order:
@sorted_array = sort { $b <=> $a } @array;
iterate through an array
( categories: array )- BASIC
The general way of iteration is using foreach:
# print all elements of an array
foreach my $element ( @array )
{
print $element . "\n";
}
- ADVANCED
If you want to iterate through an array to obtain a subset of its elements you may use grep:
# get all elements that begin with 'fun'
@fun_array = grep /^fun/ @array;
If you want to do something to each element of an array, you can use map:
# convert all elements to lowercase
@lowercase = map { lc } @array;
get the size of an array
( categories: array )Use the array in scalar context to get the size (number of elements) of the array. To force an array to be evaluated in scalar context, use the scalar operator.
Example:
print "Size of array is " . scalar @array;
remove and/or replace sections of an array
( categories: array )Use the 'splice' function. The syntax is:
splice @array, $offset, $length, @list
where:
- @array is the target array
- $offset is the starting array element to remove. The first element is 0. If '$offset' is negative it starts counting from the end of the array
- $length is the number of array elements to remove
- @list (optional) is a list of elements that will replace the element removed
return value:
In scalar context, 'splice' returns the last element removed. In list context returns the list of elements removed from the array.
