[comp.lang.perl] Aha! A stable sort

merlyn@iwarp.intel.com (Randal L. Schwartz) (05/17/91)

In article <5855@taux01.nsc.com>, arielf@tasu8c (Ariel Faigon) writes:
| 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.

Incredible, because this also leads to a simple stable sort.  Watch:

%index = ();
$delim = "\377FoObAr\377";
for (@array) {$index{&arb_function($_)} .= "$_$delim";}
@array = ();
for (@index{sort keys index}) {push(@array, split(/$delim/, $_));}

Now @array has been stable sorted according to the discriminating
value returned by &arb_function() which could then also be subject to
further perversions via a sort function in that last line.

Incredible.  Neat.

print "Just another Perl hacker,"
-- 
/=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III      |
| merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn |
\=Cute Quote: "Intel: putting the 'backward' in 'backward compatible'..."====/