Arrays

The sort function

The sort function receives a list of variables (or an array) and returns the sorted list.

Example:

  @array2 =  sort   (@array1);
  _______   ______  ___________
 
# return   function  argument
# value

Note that @array1 remains unchanged!

Example:

#!/usr/bin/perl

@countries = ("Israel", "Denmark", "France", "Mexico");
@sorted_countries = sort ( @countries);

print "ORIG:    @countries\n",
      "SORTED:  @sorted_countries\n";

Output:

ORIG:    Israel Denmark France Mexico
SORTED:  Denmark France Israel Mexico

Example:

#!/usr/bin/perl

@numbers = (1 ,2, 4, 16, 18, 32, 64);
@sorted_num = sort (@numbers);

print "ORIG:    @numbers \n",
      "SORTED:  @sorted_num \n";

Output:

ORIG:    1 2 4 16 18 32 64
SORTED:  1 16 18 2 32 4 64

Note that sorting numbers does not happen numerically, but by the string values of each number.


Table of Contents.
Previous | Next.