sort array

Discussion in 'Perl Misc' started by Shiraz, Nov 30, 2006.

  1. Shiraz

    Shiraz Guest

    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?

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


    thanks in advance;
    Shiraz, Nov 30, 2006
    1. Advertisements

  2. Shiraz

    boyd Guest

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

    boyd, Nov 30, 2006
    1. Advertisements

  3. Shiraz

    usenet Guest

    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] );
    usenet, Nov 30, 2006
  4. Shiraz

    Shiraz Guest

    thanks all.

    Shiraz, Dec 1, 2006
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.