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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |