Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get ranges from a list of integers in Perl?

Tags:

arrays

perl

I have an array of numbers:

@numbers = 1,2,3,6,8,9,11,12,13,14,15,20

and I want to print it this way:

1-3,6,8-9,11-15,20

Any thoughts? Of course I tried using the most common "looping", but still didn't get it.

like image 743
Suezy Avatar asked Dec 03 '22 12:12

Suezy


1 Answers

You can use Set::IntSpan::Fast:

use Set::IntSpan::Fast;

my @numbers = (1,2,3,6,8,9,11,12,13,14,15,20);

my $set = Set::IntSpan::Fast->new;
$set->add(@numbers);
print $set->as_string, "\n";
like image 197
cjm Avatar answered Jan 15 '23 05:01

cjm