Jun 22, 2008

Sort an Array

1) For number Array

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array = (20,10,50,40,30); #Unsorted Number Array
print "\n Unsorted Array is: @array";
my @sorted = sort { $a <=> $b } @array;

# '<=>' for numbers only
# 'cmp' used for numbers as well as strings
print "\n sorted Array is: @sorted";
my @sorted = sort { $a cmp $b } @array;

print "\n sorted Array is: @sorted";


2) For String Array

#!F:\Perl\bin\perl -w
use Data::Dumper;
#Unsorted String Array
my @array = qw/sandhya eswar prabhath vamsi/;
print "\n Unsorted Array is: @array";

my @sorted = sort { $a cmp $b } @array;

# 'cmp' can be used for both strings as well as numbers
print "\n sorted Array is: @sorted";

No comments:

Post a Comment