Perl | Reverse an array
Reverse an array or string in Perl.
Iterative Way:
Iterate over the array from 0 to mid of array.
Swap the arr[i] element with arr[size-i] element.
#Perl code to reverse an array iteratively #declaring an array of integers @arr = (2, 3, 4, 5, 6, 7); # Store length on array in $n variable $n = $#arr; #Print the original array print "The original array is : "; for $i (0 .. $#arr) { print $arr[$i], " "; } #run a loop from 0 to mid of array for my $i (0 .. $#arr/2) { #swap the current element with size-current element $tmp = $arr[$i]; $arr[$i] = $arr[$n-$i]; $arr[$n-$i] = $tmp; } #Print the reversed array print "\nThe reversed array is : "; for $i (0 .. $#arr) { print $arr[$i], " "; } |
chevron_right
filter_none
Output:
The original array is : 2 3 4 5 6 7 The reversed array is : 7 6 5 4 3 2
Using Inbuilt Function:
Perl has an inbuilt function to reverse an array or a string or a number.
#Perl code to reverse an array using inbuilt function reverse #declaring an array of integers @arr = (2, 3, 4, 5, 6, 7); #Print the original array print "The original array is : "; for $i (0 .. $#arr) { print $arr[$i], " "; } #store the reversed array in @rev_arr @rev_arr = reverse(@arr); #Print the reversed array print "\nThe reversed array is : "; for $i (0 .. $#rev_arr) { print $rev_arr[$i], " "; } |
chevron_right
filter_none
Output:
The original array is : 2 3 4 5 6 7 The reversed array is : 7 6 5 4 3 2
Recommended Posts:
- Perl | reverse() Function
- Sort an array where a subarray of a sorted array is in reverse order
- Perl | Array pop() Function
- Perl | Useful Array functions
- Perl | Array Slices
- Perl | Getting the Number of Elements of an Array
- First string from the given array whose reverse is also present in the same array
- Perl | Basic Syntax of a Perl Program
- Reverse an array in Java
- C Program to Reverse Array of Strings
- Reverse an array in groups of given size
- Sorting array with reverse around middle
- Reverse an array upto a given position
- Reverse an array in groups of given size | Set 2 (Variations of Set 1 )
- Reverse an array without affecting special characters
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



