Smart sorting

To sort alphanumerical and numerical mixed data in PERL using the sort function will not provide you the results that you will expect. If this case, you have to use the cmp command to sort the data… But your numerical data will be sort in this order: 1, 10, 11… which isn’t pretty. Thus, you could use this function:

sub smart_sort ( $ $ )
	my ($a,$b) = @_;
	# Numerical sort
	return ($a <=> $b) if (($a =~ /^\d+$/)&&($b =~ /^\d+$/));
	# Alpha sort
	return ($a cmp $b) if ($a.$b =~ /^\w+$/);
	return ($a cmp $b) if ($a.$b =~ /^\d+\w+$/);
	return ($a cmp $b) if ($a.$b =~ /^\w+\d+$/);

Then, in your code, call this function in this way:

foreach my $data (sort {&smart_sort($a,$b)} keys %HASH)

Now, your mixed data will be sorted as 1, 2, … A, B, C…

Submit a Comment

Spam Protection by WP-SpamFree