I may have the wrong forum. p5p isn't it, and clp.misc would miss the
point entirely. And this was a nice diversion for a few minutes at
work...even though I never found an answer.
While tinkering with a problem at work (listed below) I was considering
why perl couldn't have an in-place sort function. #perl noted that this
could be done in XS, certainly. I thought maybe this was worthy of
hacking into Perl itself as a use for void (or scalar) context sort().
But then a thought occurred. Within a sort block, $a and $b are just
aliases to the list being processed. Would it be possible to do something
like this:
@dummy=sort {
$r=$a cmp $b;
if ($r < 0) {
($a,$b)=($b,$a);
$r=1;
}
$r;
} @list;
# Is @list sorted? Not quite...
Except this doesn't work. Oh, $a and $b get modified and they're swapped
at appropriate times, but the resulting mess in @list can hardly be called
proper ordering.
I guess the questions are: 1. why doesn't this work? and 2. can it be
made to work?
Further, what could a read/write $a and $b be used for within a sort
block that might be considered useful?
======
Just in case I've got an XY problem (and to some extent I do), here's
what I was looking for in Real Life that got me thinking about this.
I've got an impossibly large structure in memory that resembles:
$rdb={
key1 => [
{ k1 => 'blah', k2 => 'blah2' },
{ k1 => 'blah', k2 => 'blah2' },
{ k1 => 'blah', k2 => 'blah2' },
{ k1 => 'blah', k2 => 'blah2' },
{ k1 => 'blah', k2 => 'blah2' },
# And so on and on and on...ad nauseam
],
key2 => [
{ k1 => 'foo', k2 => 'foo2' },
{ k1 => 'foo', k2 => 'foo2' },
{ k1 => 'foo', k2 => 'foo2' },
{ k1 => 'foo', k2 => 'foo2' },
{ k1 => 'foo', k2 => 'foo2' },
{ k1 => 'foo', k2 => 'foo2' },
# And so on and on and on...ad nauseam
],
# And keys to the end of the universe it seems....
}
And within each of the outer keys I have to have the inner keys
in a particular order. So I've got this code:
foreach my $database (keys %$rdb) {
my $db=$rdb->{$database};
$rdb->{$database}=[ sort {
$a->{k1} cmp $b->{k2}
} @$db ];
}
Which causes perl to throw these huge structures on a stack just
to take a reference to it and stick the reference exactly where it
was before.
Perl is eating memory for lunch here.
With relish and mustard.
Yes I can create an alternate index, sort that, and use that to reference
the array but I was going for simplicity (and diversion!) here. Someone
else needs to maintain the code and the other ends of the problem
(filling the structure and using it) are out of my control for the moment.
--
Clinton A. Pierce Teach Yourself Perl in 24 Hours *and*
[EMAIL PROTECTED] Perl Developer's Dictionary
"If you rush a Miracle Man, for details, see http://geeksalad.org
you get rotten Miracles." --Miracle Max, The Princess Bride