Sorting arrays of intervals in perl?

I have an array in perl at some intervals, for example:

@array = qw (1-5 7-9 10-15 20-58 123-192 234-256)

I am trying to order it using sorting, but this is what I get:

1-5, 10-15, 123-192, 20-58, 234-256, 7-9

It is sorted by the first character of the first number ... How can I sort by the entire first number to get the next array?

1-5, 7-9, 10-15, 20-58, 123-192, 234-256

Many thanks!

PS

I have no code for this, I'm trying to execute a command

my @sorted = sort @array;
+4
source share
2 answers

You need to extract the first number for each element and perform a numerical comparison using the operator <=>,

my @array = qw(1-5 7-9 10-15 20-58 123-192 234-256);
my @sorted = sort {
  my ($aa,$bb) = map /^([0-9]+)/, $a,$b; 

  $aa <=> $bb;
} @array;
+5
source

, . , . :

my @sorted = sort @array;

:

my @sorted = sort { $a cmp $b } @array;

cmp - ( , ). <=>, " ".

my @sorted = sort { $a <=> $b } @array;

, , 7-9, ( , , Argument "7-9" isn't numeric in sort).

, , . : /\d+/g. .

my @sorted = sort {
                     my ($a1, $a2) = $a =~ /\d+/g;
                     my ($b1, $b2) = $b =~ /\d+/g;
                     $a1 <=> $b1 || $a2 <=> $b2;
} @array;

, , . , , $a1 $b1 , <=> 0, || $a2 <=> $b2.

, , , . , .. . ref [ ... ]. :

my @sorted = map  { $_->[0] }                # restore original
             sort { $a->[1] <=> $b->[1] }    # sort compares stored nums
             map  { [ $_, /\d+/g ] }         # store original, and nums
             @array;

, $a->[2] <=> $b->[2] ..

+5

All Articles