sort array

S

Shiraz

I need take a delimited line and convert it into a new line with the
fields in the required order.

eg: $data = 'e1;e2;e3'; and the new order is 3,1,2 then the new line
need to be 'e3;e1;e2'.

i have used the code below to do this. are there any more effecient
ways to accomplish this?



_BEGIN_
use strict;
use warnings;

my $data = 'q;a;b;c;d;e;f;g;h;i';
my @NewOrder = (9,2,5,1,6,3,4,7,8,0);
my $delimiter = ';';
my @Record = split($delimiter, $data);
my @NewRecord = ();

foreach (@NewOrder)
{
push(@NewRecord, $Record[$NewOrder[$_]]);
}

@NewRecord = reverse(@NewRecord);

print join(";", @NewRecord);

_END_

thanks in advance;
GD
 
B

boyd

Shiraz said:
I need take a delimited line and convert it into a new line with the
fields in the required order.

eg: $data = 'e1;e2;e3'; and the new order is 3,1,2 then the new line
need to be 'e3;e1;e2'.

i have used the code below to do this. are there any more effecient
ways to accomplish this?



_BEGIN_
use strict;
use warnings;

my $data = 'q;a;b;c;d;e;f;g;h;i';
my @NewOrder = (9,2,5,1,6,3,4,7,8,0);
my $delimiter = ';';
my @Record = split($delimiter, $data);
my @NewRecord = ();

foreach (@NewOrder)
{
push(@NewRecord, $Record[$NewOrder[$_]]);
}

@NewRecord = reverse(@NewRecord);

print join(";", @NewRecord);

_END_

thanks in advance;
GD

I believe you can do this:
@NewRecord = @Record[@NewOrder]; # an array slice

Boyd
 
U

usenet

Shiraz said:
eg: $data = 'e1;e2;e3'; and the new order is 3,1,2 then the new line
need to be 'e3;e1;e2'.

my $data = 'q;a;b;c;d;e;f;g;h;i';
my @NewOrder = (9,2,5,1,6,3,4,7,8,0);
print(join ';', (split(/;/, $data))[@NewOrder] );
 
S

Shiraz

thanks all.

Shiraz said:
eg: $data = 'e1;e2;e3'; and the new order is 3,1,2 then the new line
need to be 'e3;e1;e2'. my $data = 'q;a;b;c;d;e;f;g;h;i';
my @NewOrder = (9,2,5,1,6,3,4,7,8,0);
print(join ';', (split(/;/, $data))[@NewOrder] );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,202
Latest member
MikoOslo

Latest Threads

Top