Skip to content

Instantly share code, notes, and snippets.

@pdl
Created October 17, 2012 22:24
Show Gist options
  • Save pdl/3908722 to your computer and use it in GitHub Desktop.
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
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