Hi Chris,

On Tue, 17 Jan 2012 21:31:49 -0600
Chris Stinemetz <chrisstinem...@gmail.com> 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.

You have not defined *how* you wish to sort the elements that have a numeric
value inside the square brackets, so I assume a simple lexicographical sort
(which should be easy to change to any other sort).

What I would do is filter the indexes of the relevant items from @array, sort
them and then re-assign the items. Here is some tested code for that:

[CODE]
#!/usr/bin/perl

use strict;
use warnings;

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]);

my @relevant_indexes = grep { $array[$_] =~ m{\[\d+\]} } (0 .. $#array);
my @sorted_indexes = sort { $array[$a] cmp $array[$b] } @relevant_indexes;

@array[@relevant_indexes] = @array[@sorted_indexes];

print map { "$_\n"} @array;
[/CODE]
 
Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Rethinking CPAN - http://shlom.in/rethinking-cpan

Dax: yep, space. Nothing but nothing all around.
    — Star Trek, “We, the Living Dead” by Shlomi Fish

Please reply to list if it's a mailing list post - http://shlom.in/reply .

--
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