iDev
iDev

Reputation: 2433

Sort numbers with the format x.x.x.x in 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

Upvotes: 6

Views: 1004

Answers (3)

NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5203

This may be easier for you to comprehend:

sub min { $_[0] <= $_[1] ? $_[0] : $_[1] }
sub comp 
  {
  ($a1,$a2) = @_;
  @a1 = @{$a1};
  @a2 = @{$a2};
  for (0..min(scalar @a1,scalar @a2)) 
     {
     return 1 if $a1[$_] > $a2[$_];
     return -1 if $a2[$_] > $a1[$_];  #exit early if an inequality is found
     }
  return 0 if @a1 == @a2; #both array are equal, thus both numbers are equal
  return @a1 > @a2 ? 1 : -1; #arrays are equal upto a certain point, thus longer array is 'greater'
  }
@sourcearray = ('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');
@individual = map { [split /\./] } @sourcearray; #splits each number into arrays consisting of individual numbers
@sorted = sort {comp($a,$b)} @individual; #sort algo decides which of these two arrays are 'greater'
{
local $" = ".";
print "@{$sorted[$_]}\n" for 0..$#sorted;
}

Upvotes: 0

ikegami
ikegami

Reputation: 386361

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.

Upvotes: 11

Kenosis
Kenosis

Reputation: 6204

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!

Upvotes: 4

Related Questions