Don't know if this solution is really preferable to any of the others, but its got a  s/// in there! Uses state feature (available with 5.10+), but could easily avoid it. Note that it does not bother to range-ize a degenerate range: '1,2' does not become '1-2'.

>perl -wMstrict -le "use feature 'state'; ;; my $s = '2,3,5,6,7,9,11,12,13,14,16,17,19'; print qq{'$s' \n}; ;; my $sep = qr{ \s* , \s* }xms; my $n = qr{ \d+ }xms; ;; sub order { state $p = 0; my $t = $p; $p = $_[0]; return $_[0] - $t == 1; } ;; use re 'eval'; $s =~ s{ (?<! \d) ($n) (?{ order($^N) }) (?= $sep ($n) (?(?{ ! order($^N) }) (*F)) (?: $sep ($n) (?(?{ ! order($^N) }) (*F)))+ ) .+? \3 (?! \d) } {$1-$3}xmsg; ;; print qq{'$s' \n}; " '2,3,5,6,7,9,11,12,13,14,16,17,19' '2,3,5-7,9,11-14,16,17,19'

Update: Actually, the non-capturing look-ahead folderol is not needed. The following  s/// seems to work just as well.

$s =~ s{ (?<! \d) ($n) (?{ order($^N) }) (?: $sep ($n) (?(?{ ! order($^N) }) (*F))){2,} } {$1-$2}xmsg;

Update: Even slightly simpler and no numbered capture group variables, but  \K only available with 5.10+, like state.

sub order { state $p = 0; my $t = $p; $p = $^N; return $^N - $t == 1; } $s =~ s{ (?<! \d) ($n) \K (?{ order() }) (?: $sep ($n) (?(?{ ! order() }) (*F))){2,} } {-$^N}xmsg;

In reply to Re^2: Converting a list of numbers to use a range operator by AnomalousMonk
in thread [Solved] Converting a list of numbers to use a range operator by FloydATC

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.