--- Paul Johnson <[EMAIL PROTECTED]> wrote:
> On Wed, May 16, 2001 at 10:05:14AM -0700, Matt Noel wrote:
> > I have a simple two-dimensional array, call it @Weights. I think
> > of the first index as being the Row index and the second being the
> > Column index. Normally I'd access an entry thus:
> >
> > $ItemWeight = $Weights[$row][$col];
> >
> > I just want to sort the rows first by the first column, then by the
> > second column, etc for all the columns.
>
> You'll be wanting to use the spaceship operator <=>
True for numeric data (which you said this is).
With strings, use "cmp". cmp works for numerals also, but sorts 20 in
front of 3.....
> The key to the solution, is that if the values being compared are the
> same, the operator will return 0, and you can then use the
> short-circuiting || operator to only check the next column if
> necessary.
"or" also short circuits, and some consider it more readable, but it
(and the "and" operator) always return(s) a boolean value, while ||
(and &&) return the value of the first true expression.
$a or $b # returns 1 if either has a non-false value, else ''
$a || $b # returns $a if nonfalse, else $b if nonfalse, else ''
> So, something like:
>
> my @sorted = sort {
> $a->[0] <=> $b->[0]
> ||
> $a->[1] <=> $b->[1]
> ||
> $a->[2] <=> $b->[2]
> } @Weights;
Nice. =o)
But for explanation, sort passes in elements from the array being
sorted as $a and $b. Since this is a 2D array, the elements of the
first dimension are references to the second-dimensional sub-arrays.
Thus, @{$a} is the entire sub array, and $a->[0] means "give me element
zero of the array poited to by $a". Paul is sorting the first dimension
elements by the values in the second dimension elements. =o)
Please forgive me for explaining someone else's post and adding little
of my own, but I liked this -- it was reasonably elegant -- but it took
me a moment to figure out exactly what he was doing. I thought it might
give real novices a headache, but exposing some of what's under it's
hood might do them good. ;o]
Paul
=====
print "Just another Perl Hacker\n"; # edited for readability =o)
=============================================================
Real friends are those whom, when you inconvenience them, are bothered less by it than
you are. -- me. =o)
=============================================================
"There are trivial truths and there are great Truths.
The opposite of a trival truth is obviously false.
The opposite of a great Truth is also true." -- Neils Bohr
__________________________________________________
Do You Yahoo!?
Yahoo! Auctions - buy the things you want at great prices
http://auctions.yahoo.com/