The sort Operator

The sort operator takes a list of values (which may come from an array) and sorts them in the internal character ordering.  For ASCII strings, that would be ASCIIbetical order.  Of course, ASCII is a strange place where all of the capital letters come before all of the lowercase letters, where the numbers come before the letters, and the punctuation marks - well, those are here, there, and everywhere.  But sorting in ASCII order is just the default behavior; we'll see in a later lesson Strings and Sorting, how to sort in whatever order you'd like:

	@rocks = qw/ bedrock slate rubble granite /;
	@sorted = sort(@rocks);				# gets bedrock, granite, rubble, slate
	@back = reverse sort @rocks;			# these go from slate to bedrock
	@rocks = sort(@rocks);				# puts sorted result back into @rocks
	@numbers = sort 97..102;			# gets 100, 101, 102, 97, 98, 99

As you can see by that last example, sorting numbers as if they were strings may not give useful results.  But, of course, any string that starts with 1 has to sort before any string that starts with 9, according to the default sorting rules.  And like what happened with reverse, the arguments themselves aren't affected.  If you want to sort an array, you must store the result back into that array:

	sort @rocks;		# WRONG - doesn't modify @rocks
	@rocks = sort @rocks;	# Now the rock collection is in order
Next:  Interpolating Arrays Into Strings

OR

Main Menu for this topic