perltutorial vroom Ever wanted to sort on a computed value or a certain column in a string within an array. It can get pretty tricky to do right. You only want to compute the value you're sorting on once for each array element not every time you do a comparison throughout the sort.<BR> <BR> One key function you'll want to know how to use is [map]. Map allows you to apply a change to a list and get back a new list with the changes.<BR> <BR> There are two ways you can use the map function; <CODE> #map BLOCK, LIST #or something like @revwords=map{ @letters=split(//); @revletters=reverse(@letters); join(' ',@revletters); } @words; #or #map EXPR, LIST @asciival=map(ord,@letters); </CODE> The first example takes a list of words and returns a list of each of those words with the letters reversed. This is done by splitting them, then reversing the resulting array, and then returning the joined array which is the word reversed. The second example takes an array of letters and returns a list of their ascii values;<BR> <BR> Now say we want to sort an array that contains 3 columns of numbers separated by spaces. We want to sort this array on the sum of these three numbers.<BR> <BR> The first thing we want to do is map the original array to an array with the calculated sums, as well as the original values in it.<BR> <CODE> @origarray=('0 1 2','0 0 0','-3 -2 -1','10 11 12'); @sortedarray= map{\$_->} sort{\$a-> <=> \$b->} map{ my @cols=split(/\s+/); my \$sum=\$cols+\$cols+\$cols; [\$_,\$sum]; } @origarray; foreach(@sortedarray){ print "\$_\n"; } </CODE> We start by doing the basic transform within the innermost map. The current list value comes in as the default variable(\$_), then we split the columns, add them up, and return &#091;\$_, \$sum&#093; which contains the original value followed by the computed value for sorting on. We then sort numerically on this computed value. And then use map so the array only contains the original stuff.<BR> <BR> This whole process is known as the Schwartzian Transform.<BR> Here's a template for doing complex sorting<BR> <CODE> @sortedarray= map{\$_->} # only use one of these sort lines sort{\$a-> <=> \$b->} # this one for numerical sorting sort{\$a-> cmp \$b->} # this one for textual sorting map{ #calculate \$computedsortval [\$_,\$computedsortval]; } @origarray; </CODE> This should hopefully give you a better understanding of what is going on when you need to do a complex sort, and hopefully allow you to do it right with very little hassle.