Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort numbers with the format x.x.x.x in perl

Tags:

sorting

perl

Say for example the numbers are in format :

1.1.10
1.1.10.1
1.1.10.2
1.1.11
1.1.12
1.1.13
1.1.13.1
1.1.3
1.1.4

And the wat I am looking for output is :

1.1.3
1.1.4
1.1.10
1.1.10.1
1.1.10.2
1.1.11
1.1.12
1.1.13
1.1.13.1
like image 457
iDev Avatar asked Jul 20 '12 18:07

iDev


2 Answers

use Sort::Key::Natural qw( natsort );
my @sorted = natsort @data;

or (no modules)

my @sorted =
   map $_->[0],
   sort { $a->[1] cmp $b->[1] }
   map [ $_, pack('C*', split /\./) ],
   @data;

or (no modules, faster, but requires an array rather than a list for input)

 my @sorted =
   map $data[unpack('N', $_)],
   sort
   map pack('NC*', $_, split /\./, $data[$_]),
   0..$#data;

In the pack templates, you can change C to n or N. C allows numbers up to 255. n allows numbers up to 65,535. N allows numbers up to 4 billion.

like image 174
ikegami Avatar answered Oct 19 '22 18:10

ikegami


Try the following:

use Modern::Perl;
use Sort::Naturally  qw{nsort};

my @numbers = nsort(qw{1.1.10 1.1.10.1 1.1.10.2 1.1.11 1.1.12 1.1.13 1.1.13.1 1.1.3});
say for @numbers;

Output:

1.1.3
1.1.10
1.1.10.1
1.1.10.2
1.1.11
1.1.12
1.1.13
1.1.13.1

Hope this helps!

like image 24
Kenosis Avatar answered Oct 19 '22 19:10

Kenosis