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

my @numbers = ( 1,2,4,5,6,7,9,13,24,25,26,27);
print "Beginning with this list:\n";
print "$_ " for @numbers;

print "\n\nformat_number_list turns it into this:\n";
my $list = format_number_list( @numbers );
print $list;

print "\n\nexpand_number_list turns *that* into this:\n";

print "$_ " for expand_number_list( $list );


#########
sub format_number_list{
	my @num = @_;
	my $out = '';
	my $run_start;
	my $i;
	for( $i=0; $i<$#num; $i++ ){
		if( $num[$i] == ($num[$i+1] - 1) ){
			$run_start = $num[$i] unless( defined ($run_start) );
		}
		else{
			if( defined $run_start ){
				$out .= "$run_start-";
				undef $run_start;
			}
			$out .= "$num[$i], ";
		}
	}
	# last element
	if( defined $run_start ){
		$out .= "$run_start-";
	}
	$out .= "$num[$#num]";

	return $out;
}

sub expand_number_list{
	my $list = shift;
	my @list = split /, /, $list;
	my @out = ();
	foreach(@list){
		if( /^(\d+)-(\d+)$/ ){
			push @out, ($1 .. $2);
		}
		else{
			push @out, $_;
		}
	}
	return @out;
}

