#!/usr/bin/perl use strict; use warnings; my @nums = split / /, shift; my ($have_begin, $have_inc, $not_follow_inc, $str); for (my $i = 0; $i < @nums; $i++) { no warnings 'uninitialized'; if (!$have_begin && !$not_follow_inc) { $str .= $nums[$i]; $have_inc = $nums[$i]; $have_begin = 1; } elsif (($nums[$i+1] - $nums[$i]) == 1) { $have_inc++; } elsif ($not_follow_inc) { $str .= ', ' . $nums[$i]; $str .= ', ' if $i != $#nums; $not_follow_inc = 0; } else { $str .= '-'.++$have_inc; $have_begin = 0; $not_follow_inc = 1; } } print "$str\n"; __INPUT__ 1 2 3 5 7 8 9 __OUTPUT__ 1-3, 5, 7-9