#!/usr/local/bin/perl -w
use strict;

printf "Result 1 = \"%s\"\n", format_number_list(1, 2, 4, 5, 6, 7, 9, 13, 24, 25, 26, 27) ;
printf "Result 2 = \"%s\"\n", format_number_list(1, 4, 5, 6, 7, 9, 13, 24, 25, 26, 27, 30) ;
my @result3 = expand_number_list("1-2, 4-7, 9, 13, 24-27") ;
print "Result 3 = (@result3)\n" ;
my @result4 = expand_number_list("1, 4-7, 9, 13, 24-27, 30") ;
print "Result 4 = (@result4)\n" ;

sub format_number_list {
    my @list = (@_, 0.9) ;                            ## Append 0.9 as delimiter
    my $previous = my $result = shift @list ;
    foreach my $current (@list) {
	if ($current == $previous+1) {
	    $result .= '-' unless $result =~ (/-$/) ; ## Compacting ...
	} else {
	    $result .= ($result =~ /-$/) ? "$previous, $current" : ", $current" ;
	}
	$previous = $current ;
    }
    $result =~ s/, 0.9$// ;                           ## Remove the delimiter
    $result ;                                         ## and return
}

sub expand_number_list {
    my @result ;
    foreach my $num (split(/\s*,\s*/, $_[0])) {
	push(@result, ($num =~ /(\d+)\s*-\s*(\d+)/) ? ($1 .. $2) : $num) ;
    }
    @result ;
}

