nop has asked for the wisdom of the Perl Monks concerning the following question:

I think if I weren't on heavy doses of cold medicine I'd be able to figure this one out. But as I am, and my head is fogged out, I'm turning to the Helpful Community for help. I have an array that is sorted alpha:
@a = qw(a d v x)
I do some substitutions, say a->t and v->z, yielding
@newa = ('t', 'd', 'z', 'x')
More often than not, these substitutions take  @newa out of alphabetical order.

I'm seeking the sort index @sortindex that such that
@newa[@sortindex]
is alphabetized... I don't just want  sort @newa, I need the sortindex... Cant quite get the Schwartzian Transform right... Thanks...

nop

cough cough hack sneeze

Replies are listed 'Best First'.
Re: sort index (head cold)
by kschwab (Vicar) on Feb 02, 2001 at 21:16 UTC
    How about:
    @sortindex=sort { $newa[$a] cmp $newa[$b] } (0..$#newa);
      Many thanks! This solved a deep bug. Appreciate it.
Re: sort index (head cold)
by Fastolfe (Vicar) on Feb 02, 2001 at 21:17 UTC
    Update: I think I misunderstood the problem; disregard.

    If you mean to pull out the indexes for the first set of "sorted" data (e.g. the first set of elements where the next is greater than the previous), something like this should work:

    @a = (9, 8, 7, 4, 5, 6, 3, 2, 1); # index 3..5 is wanted @index = grep { $a[$_+1] > $a[$_] .. $a[$_+1] <= $a[$_] } 0..$#a-1; print "found index @index = @a[@index]\n";
Re: sort index (head cold)
by coolmichael (Deacon) on Feb 05, 2001 at 12:14 UTC
    I'm not quite sure I understand your question, but I think I do. I think a hash would be the easiest way to go.
    #!/usr/bin/perl -w use strict; my (@newa, %hash, @sortedlist, @sortedindex); @newa = ('t', 'd', 'z', 'x'); @hash{@newa}=(0..$#newa); @sortedlist=sort @newa; @sortedindex=@hash{@sortedlist}; print "@sortedindex\n"; print "@newa[@sortedindex]\n";
    I don't think this is particularly efficient, but it does give the result I think you want. It might be easier to use map, but I haven't figured map out yet.
    1 0 3 2 d t x z
    is the output.