Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Sorting Arrays

by zdog (Priest)
on Jun 26, 2000 at 08:41 UTC ( [id://19803]=perlquestion: print w/replies, xml ) Need Help??

zdog has asked for the wisdom of the Perl Monks concerning the following question:

Let's say I have the following array of arrays:

@array = ( [ "array1name", "array1info", "array1num" ], [ "array2name", "array2info", "array2num" ], [ "array3name", "array3info", "array3num" ], );

Now, how can I sort the arrays within the array according to the value of 'array#num' in descending order.

Thanks in advance.

-- Zenon Zabinski

Replies are listed 'Best First'.
Re: Sorting Arrays
by nardo (Friar) on Jun 26, 2000 at 09:27 UTC
    @sorted = sort {@{$b}[2] cmp @{$a}[2]} @array;
      Nope. You're using an array slice @x[$y] where you really want an element $x[$y]. And as pointed out elsewhere, you're using cmp where you want <=>.

      -- Randal L. Schwartz, Perl hacker

      Thanks for the help. And now that I think about it, I probably should have got it on my own, but when I go into unchartered territory (functions that I have never used before), my brain freezes. Thanks again.

      -- zdog (Zenon Zabinski)
         Go Bells!! '¿'

        if array#num is really a number, <=> might be a better option ...
        @array = sort { $$a[2] <=> $$b[2] } @array;
        --
        Greg McCarroll
        http://www.mccarroll.uklinux.net
      Thanks for the tip. I used this to sort my array[][][]. I was able to sort my list by an object property as follows:
      @memory_blocks = sort {hex(${$b}[0][0]->address) <=> hex(${$a}[0][0]-> +address)} @memory_blocks;
      Hope that might help someone else who gets stuck. Thanks again!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://19803]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2024-04-26 04:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found