我有一个包含使用此语法的参数的文件
RANGE {<value> | <value>-<value>} [ , ...]
Run Code Online (Sandbox Code Playgroud)
其中values是数字.
例如,所有这些都是有效的语法
RANGE 34
RANGE 45, 234
RANGE 2-99
RANGE 3-7, 15, 16, 2, 54
Run Code Online (Sandbox Code Playgroud)
如何在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? >
}
}
Run Code Online (Sandbox Code Playgroud)
我需要帮助解析数字.为了解析,我能想到的一个方法是使用连续的分裂(上-,,和).是否有更好的(干净和优雅,使用正则表达式?)方式?
此外,欢迎就整个计划结构提出意见/建议.
看看Text::NumericListCPAN的模块.它可以以您需要的类似方式将字符串转换为数组:
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)
Run Code Online (Sandbox Code Playgroud)
您至少可以查看其源代码以获取创意.
| 归档时间: |
|
| 查看次数: |
915 次 |
| 最近记录: |