Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by length in Perl

Tags:

sorting

perl

Anyone have any idea how to sort number by length?

Ex : (11,111,122,12,2,13,21,15,211,22,213,2004)

I wanted the sorted array to be:

11
12
13
15
111
122
2
21
22
213
2004
like image 518
Tom Erdos Avatar asked Dec 20 '22 13:12

Tom Erdos


1 Answers

The desired output seems to indicate you don't just want to sort by the number of digits, but rather first sort by the first digit and then by the length.

The desired output you show omits 211, so I just put it where it belonged according to my understanding.

#!/usr/bin/env perl

use strict;
use warnings;

use Test::More;

my @source = (11, 111, 122, 12, 2, 13, 21, 15, 211, 22, 213, 2004);
my @desired = (11, 12, 13, 15, 111, 122, 2, 21, 22, 211, 213, 2004);

my @sorted =sort {
    substr($a, 0, 1) <=> substr($b, 0, 1) ||
    length($a) <=> length($b) || 
    $a <=> $b # thanks @ikegami
} @source;

is_deeply(\@sorted, \@desired, 'Sorted and desired are the same');
like image 106
Sinan Ünür Avatar answered Jan 12 '23 23:01

Sinan Ünür