3

I have a big array and I want to sort all the elements of the array in alphabetical order.

In a previous subroutine, the element of the array are being pushed to tc_reg array.

I have an array named @tc_lane. When I print element of the array it would look something like this

tx0_abc
rx0_fgw
ref_ghv
..

Now I want to sort this array like this,

ref_ghv
rx0_fgw
tx_abc
..
6
  • 2
    @arr = sort @arr; - please delete this question. Commented Jul 8, 2019 at 21:03
  • 2
    @SeanBright why delete? it's a simple question, but with a little bit of looking I don't see any existing question it duplicates; most sort questions are dealing with more complicated situations. Commented Jul 8, 2019 at 21:07
  • Possible duplicate of Sort Perl array in place? Commented Jul 8, 2019 at 21:07
  • That's sorting an array in place where you have a reference to the array instead of an array variable Commented Jul 8, 2019 at 21:08
  • From the linked answer: "Perl allows arrays to be sorted in-place with the idiom @arr = sort @arr." - which is precisely the answer you gave. So I'm not sure what the issue is? Commented Jul 8, 2019 at 21:11

2 Answers 2

8

If you want

rx0_fgw
rx10_fgw
rx2_fgw

use

my @sorted = sort @unsorted;

If you want

rx0_fgw
rx2_fgw
rx10_fgw

use

use Sort::Key::Natural qw( natsort );

my @sorted = natsort @unsorted;
Sign up to request clarification or add additional context in comments.

1 Comment

Both of these solutions assumes the only letters are lowercase ASCII letters. Other solutions might be needed in other situations.
2

You simply need to do:

@tc_lane = sort @tc_lane;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.