blob: 5ec92037c52713574e7a72c5e5dd7c415cb6d2e9 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
#!/usr/bin/env perl
use strict;
use warnings;
sub compact {
my @ns = split(/,/, shift);
my $from = my $to = shift @ns; # The first interval is the first number
my @intervals;
# Store the current interval ($from, $to) and advance to the next one
my $save = sub {
push(@intervals, $from == $to ? $from : "$from-$to");
$from = $to = shift;
};
# Iterate over the numbers, expanding the last interval or starting a new one
foreach my $n (@ns) {
if ($to == $n-1) {
$to = $n;
} else {
&$save($n);
}
}
# Store the last interval (except for empty input)
&$save if defined $to;
return join(",", @intervals);
}
foreach (@ARGV) {
print compact($_), "\n";
}
|