views:

55

answers:

1

Is there a module, which does this for me?

sample_input: 2, 5-7, 9, 3, 11-14

#!/usr/bin/env perl
use warnings; use strict; use 5.012;

sub aw_parse {
    my( $in, $max ) = @_;
    chomp $in;
    my @array = split ( /\s*,\s*/, $in );
    my %zahlen;
    for ( @array ) {
    if ( /^\s*(\d+)\s*$/ ) {
        $zahlen{$1}++;
    }
    elsif ( /^\s*(\d+)\s*-\s*(\d+)\s*$/ ) { 
        die "'$1-$2' not a valid input $!" if $1 >= $2;
        for ( $1 .. $2 ) {
        $zahlen{$_}++;
        }
    } else {
        die "'$_' not a valid input $!";
    }
    }
    @array = sort { $a <=> $b } keys ( %zahlen );
    if ( defined $max ) {
    for ( @array ) {
        die "Input '0' not allowed $!" if $_ == 0;
        die "Input ($_) greater than $max not allowed $!" if $_ > $max;
    }
    }
    return \@array;
}

my $max = 20;
print "Input (max $max): ";
my $in = <>;
my $out = aw_parse( $in, $max );
say "@$out";
+6  A: 

A CPAN search for number range gives me this, which looks pretty much like what you're looking for:

Number::Range

Here's an example of how you can use the module in your aw_parse function:

$in =~ s/\s+//g; # remove spaces
$in =~ s/(?<=\d)-/../g; # replace - with ..

my $range = new Number::Range($in); # create the range
my @array = sort { $a <=> $b } $range->range; # get an array of numbers

Applied to the sample from the question:

Input (max 20): 2, 5-7, 9, 3, 11-14
2 3 5 6 7 9 11 12 13 14
jkramer
Why? It does exactly what sid_com is trying to do.
jkramer
+1 for giving example.
Space
@ jkramer : The example does clear up some things, I wasn't thinking along the lines of replacing `-` s with `..` s. Downvote removed. But it still doesn't replace the OP's `aw_parse` subroutine per se.
Zaid
accepted although this module needs some extra code to modify the input and the input-validation is a little less strict.
sid_com
If you're in a position where you can define the input format, I'd suggest to use the a..b syntax for ranges instead of a-b. a-b might be problematic once you need to define ranges with negative numbers. Also it removes the need for the regex.
jkramer