I needed a way for a user to specify multiple items and to have each item in an array. Basically, 21, 35, 42-45, 19 needs to be expanded to 21, 35, 42, 43, 44, 45, 19 and have each number (seperated by anything matching \s*,\s*) put in an array.

Update Push integers into @expanded instead of strings in the else block. Thanks jeffa!

Update2 Now splits on \s*,\s* (and \s*-\s* for the ranges). Thanks again to jeffa for the suggestion.

Update3 The sub will now correctly deal with reverse ranges (ex/ 42-13) as well as abbreviated ranges (ex/ 123-5 produces 123, 124, 125). 123-35 also works as expected. If you give it 123-19, it will do a reverse abbreviated range : ) producing 123, 122, 121, 120, 119.

Update4 At jeffa's suggestion, I changed my use of the ternary operator so that it is being used to assign a value instead of in void context.

sub expandRanges { my @pieces = split /\s*,\s*/, $_[0]; my @expanded = (); foreach my $piece (@pieces) { next if $piece !~ /\A[\d\-\s]+\z/; if ($piece =~ /-/) { my @tmp = split /\s*-\s*/, $piece; my $diff = length($tmp[0]) - length($tmp[1]); $tmp[1] = substr($tmp[0], 0, $diff) . $tmp[1] if $diff; push @expanded, $tmp[0] > $tmp[1] ? reverse ($tmp[1]..$tmp[0]) : ($tmp[0]..$tmp[1]) ; } else { push @expanded, int $piece; } } return @expanded; }

In reply to Expand Ranges in Lists of Numbers by The Mad Hatter

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.