Wednesday, April 26, 2006

Perl : Sorting a list/array

Sorting of a list/array can be done with sort function. Reversing the order is easy; done with the function reverse. See following code and the output.

Code :

@fruit = ("banana","mango","apple");
@sorted_fruit = sort @fruit;

$,=" "; # $, is the output field separator (a predefined variable). This is used here to put spaces after printing every element of the array.
$\="\n"; # $\ is the output record separator. Used to add a newline to print in this example.

print @sorted_fruit;

print reverse @sorted_fruit; # reverses the order in the list

Output :

apple banana mango
mango banana apple

No comments: