Is there a module for parsing numbers (inkl. ranges)?
Posted
by sid_com
on Stack Overflow
See other posts from Stack Overflow
or by sid_com
Published on 2010-05-12T07:41:40Z
Indexed on
2010/05/12
7:44 UTC
Read the original article
Hit count: 216
Is there a module, which does this for me?
#!/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";
© Stack Overflow or respective owner