Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!elroy.jpl.nasa.gov!sdd.hp.com!hplabs!nsc!taux01!tasu8c!arielf From: arielf@tasu8c.UUCP (Ariel Faigon) Newsgroups: comp.lang.perl Subject: Re: How to sort on right most column Summary: Proposed solution needs a little fix Keywords: associative-array, unique-key Message-ID: <5855@taux01.nsc.com> Date: 16 May 91 10:48:13 GMT References: <1991May15.182131.20425@uvaarpa.Virginia.EDU> Sender: netnews@taux01.nsc.com Reply-To: arielf@tasu8c.UUCP (Ariel Faigon) Organization: National Semiconductor (IC) Ltd, Israel Lines: 50 +--- In the referenced article, Barr3y Jaspan wrote: ||> 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 | | ... ] |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. [more deleted ...] +------ Barr3y's solution is of course most straight forward. One problem remains though, since associative array keys are unique, lines with the same key (same last column) will overwrite each other. The solution is to concatenate lines with the same key (the '\n' is left intact thanks to Perl). i.e. to replace the line: > $lines{$1} = $_; With $lines{$1} .= $_; This should do what the original poster wanted. Peace, Ariel Ariel Faigon National Semiconductor Corp. (NSTA Design Center) 6 Maskit St. P.O.B. 3007, Herzlia 46104, Israel Tel. +972 52-522272 arielf@taux01.nsc.com