Created
October 17, 2012 22:24
-
-
Save pdl/3908722 to your computer and use it in GitHub Desktop.
Turn an array of integers into a string of an array with ranges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use List::Util qw(reduce); | |
my @in = (1,2,3,4,5,6,8,9,10,12,16,17,18,21); | |
print join (',', | |
map { defined $_->[1] ? "$_->[0]..$_->[-1]": $_->[0] } | |
@{ | |
reduce{ | |
my $c = [$b]; | |
if (@$a and ref $a->[0]){ | |
if ($a->[-1]->[-1] + 1 == $b->[0]){ | |
push @{$a->[-1]}, $b->[0]; | |
$c = $a; | |
} | |
else { | |
push @$a, $b; | |
$c = $a; | |
} | |
} | |
elsif (!ref $a->[0]) | |
{ | |
$c = [$a, $b]; | |
} | |
$c; | |
} | |
map { [ $_ ] } | |
@in | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment