How to sort values of an array with sort() in Perl

Overview

In Perl, we can sort an array with the sort() method. It takes a single parameter, the array that needs to be sorted.

Syntax

sort(arr)

Parameters

arr: This is the array we want to sort.

Return Value

It returns a sorted array.

Example

# create arrays
@arr1 = (1, 5, 2, 4, 3);
@arr2 = ("e", "c", "a", "d", "b");
@arr3 = ("Java", "Python", "Perl", "C");
# print arrays before sort
print "Before Sort: \n
\@arr1 = @arr1\n
\@arr2 = @arr2\n
\@arr3 = @arr3";
# sort the arrays
@r1 = sort(@arr1);
@r2 = sort(@arr2);
@r3 = sort(@arr3);
# print arrays again
print "\nAfter Sort: \n
\@arr1 = @r1\n
\@arr2 = @r2\n
\@arr3 = @r3\n";

Explanation

  • Line 2–4: We create arrays.
  • Line 7: We print the array values before sorting.
  • Line 12–14: The arrays we created are sorted using the sort() method. The results were stored in variables @r1, @r2, and @r3.
  • Line 17: We printed the results to the console after sorting the arrays.

Free Resources