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
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With