我有一个包含使用此语法的参数的文件
RANGE {<value> | <value>-<value>} [ , ...]
在哪里
value
s 是数字。例如,所有这些都是有效的语法
RANGE 34
RANGE 45, 234
RANGE 2-99
RANGE 3-7, 15, 16, 2, 54
如何将值解析为 Perl 中的数组?
例如,对于最后一个示例,我希望我的数组具有
3, 4, 5, 6, 7, 15, 16, 2, 54
.元素的顺序无关紧要。最基本的方法是检查
-
判断是否存在范围的符号,使用循环解析范围,然后解析其余元素my @arr;
my $fh, "<", "file.txt" or die (...);
while (<$fh>) {
if ($_ =~ /RANGE/) {
if ($_ =~ /-/) { # parse the range
< how do I parse the lower and upper limits? >
for($lower..$upper) {
$arr[++$#arr] = $_;
}
} else { # parse the first value
< how do I parse the first value? >
}
# parse the rest of the values after the comma
< how do I parse the values after the comma? >
}
}
-
、 ,
和
上)。有没有更好的(干净优雅,可能使用正则表达式?)方式? 最佳答案
看看 Text::NumericList
来自 CPAN 的模块。它可以以您需要的类似方式将字符串转换为数组:
use Text::NumericList;
my $list = Text::NumericList->new;
$list->set_string('1-3,5-7');
my @array = $list->get_array; # Returns (1,2,3,5,6,7)
您至少可以查看其源代码以获取想法。
关于arrays - 如何将此语法解析为 Perl 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3763843/