Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Sorting multi dimensional arrays

by arturo (Vicar)
on Mar 14, 2001 at 21:49 UTC ( [id://64438]=note: print w/replies, xml ) Need Help??


in reply to Sorting multi dimensional arrays

If you have a multidimensional array, and you want to sort out the 'flattened' version (I'm wondering why you'd want to do this, but whatever), the most straightforward way is to flatten it out by writing a loop that grabs each element in each array reference and then sort the result:

my @flatarray; foreach (@twodimarray) { foreach my $element (@$_) { push @flatarray, $element; } } # for numeric data @flatarray = sort { $a <=> $b } @flatarray;

This should work on *any* 2D array, whether the array references are all the same length or not.

You might check on CPAN (search for "Array") to see if someone's written a module that can help you.

Update I spoke too quickly ... so you want to reconstruct the array with the same dimensional structure as the original? well, take appropriate-sized slices of @flatarray and write them, as anonymous arrays, back into the original format (which is pretty much what you were doing). If you're dealing with more complex data (e.g. differing row lengths) you'll have to store the original row lengths (in an array) while you're flattening it out, and reconstruct the original array from that additional information.

Philosophy can be made out of anything. Or less -- Jerry A. Fodor

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (1)
As of 2024-04-25 00:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found