On 18/01/2012 03:31, Chris Stinemetz wrote:

Would someone kindly advise me in sorting this array:

my @array = qw(c r v vr tr re c.p[1] c.p[3] c.p[2] c.p[4] c.p[7]
c.p[6] c.p[5] c.p[8] c.t[1] c.t[3] c.t[2]);

I only want to sort the elements that have a numeric value inside
the braces so that all the other elements have their original index
preserved.

Sample output I am trying to accomplish:

c r v vr tr re c.p[1] c.p[2] c.p[3] c.p[4] c.p[5] c.p[6] c.p[7]
c.p[8] c.t[1] c.t[2] c.t[3]

Is this a good example to use Schwartzian Transform?

Thanks in advance,

Hi Chris

Not really. The Schwartzian transform is used when the data should be
sorted in the order of a mapping of the data. The only way I can see to
do this is to split the indexed and non-indexed data and recombine them.

  my @sorted = (grep(!/\[\d+\]/, @array), sort grep(/\[\d+\]/, @array));

Even then, if you want to sort both numerically by index and lexically
by the 'c.x' part, the sort will need to be more elaborate if the
indices can be more than a single digit.

What exactly do you mean by "all the other elements have their original
index preserved"? If the data was like this

my @array = qw(c c.p[1] r c.p[3] v c.p[2] vr c.p[4] tr c.p[7] re c.p[6] c.p[5] c.p[8] c.t[1] c.t[3] c.t[2]);

would the non-indexed values need to remain at elements 0, 2, 4, 6, 8,
10? If so then you have a complex problem and lot of work on your hands!

HTH,

Rob

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to