是否有用于解析数字(包括范围)的Perl模块? [英] Is there a Perl module for parsing numbers, including ranges?
本文介绍了是否有用于解析数字(包括范围)的Perl模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一个模块,该模块可以帮我吗?
Is there a module, which does this for me?
sample_input:2、5-7、9、3、11-14
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";
推荐答案
CPAN搜索number range
给了我这个,它看起来很像您在寻找什么:
A CPAN search for number range
gives me this, which looks pretty much like what you're looking for:
这是一个如何在aw_parse
函数中使用该模块的示例:
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
应用于问题中的示例:
Input (max 20): 2, 5-7, 9, 3, 11-14
2 3 5 6 7 9 11 12 13 14
这篇关于是否有用于解析数字(包括范围)的Perl模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文