To rotate elements in an array using Perl, you can implement a custom rotation subroutine or use Perl's array manipulation functions.
In this example,
@int_array
containing integers.rotate_array
subroutine to rotate the array by a specified number of positions.@int_array = (1, 2, 3, 4, 5);
$positions = 2;
rotate_array(@int_array, $positions);
print "Rotated Array: [@int_array]\n";
sub rotate_array {
my ($array_ref, $positions) = @_;
@$array_ref = (@$array_ref)[$positions..$#{$array_ref}, 0..$positions-1];
}
Rotated Array: 3 4 5 1 2
In this example,
@str_array
containing strings.rotate_array
subroutine to rotate the array by a specified number of positions.@str_array = ('apple', 'banana', 'cherry', 'date', 'fig');
$positions = 3;
rotate_array(@str_array, $positions);
print "Rotated Array: [@str_array]\n";
sub rotate_array {
my ($array_ref, $positions) = @_;
@$array_ref = (@$array_ref)[$positions..$#{$array_ref}, 0..$positions-1];
}
Rotated Array: date fig apple banana cherry
In this tutorial, we learned How to Rotate Elements in an Array in Perl language with well detailed examples.