Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uwm.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!udel!haven.umd.edu!uvaarpa!mmdf From: bjaspan@ATHENA.MIT.EDU (Barr3y Jaspan) Newsgroups: comp.lang.perl Subject: Re: How to sort on right most column Message-ID: <1991May15.182131.20425@uvaarpa.Virginia.EDU> Date: 15 May 91 18:21:31 GMT Sender: mmdf@uvaarpa.Virginia.EDU (Uvaarpa Mail System) Reply-To: bjaspan@ATHENA.MIT.EDU Organization: The Internet Lines: 42 |> I have the following data in this format - I want to sort it on the |> right most column. |> |> 0 1 2 3 4 |> |> a b c c e |> |> FOO BAR ACE CORPORATION SUNNYVALE 2.00 |> FOO BAR ACER COMPUTED COMPANY MILPITAS 20.00 (Introduction: I'm not sure what the first two lines ("0 1 2 ...") are for, so I'm ignoring them. :-) Well, since you know the sort key is the last number on each line, you could do something like this (untested): while (<>) { /([\d.]+)$/; $lines{$1} = $_; } for (sort numerically keys %lines) { print $lines{$_}; } sub numerically { $a <=> $b; } The idea is to use the number at the end of a line as a key in an associative array, storing each entire line of text keyed on its final number. (You could do this more "efficiently" with a normal array if you knew (1) that all your numbers were integers and (2) that all the numbers were "small".) Then you just sort the keys and print the respective lines of text, in order. (You could also split the entire line on whitespace and use the last element in the returned array as your key; I suspect (but I'm not sure) the first way is faster.) Barr3y Jaspan, bjaspan@mit.edu