如何展开像“1..15,16"这样的字符串?变成数字列表? [英] How can I expand a string like "1..15,16" into a list of numbers?

查看:40
本文介绍了如何展开像“1..15,16"这样的字符串?变成数字列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Perl 应用程序,它从命令行获取输入:

I have a Perl application that takes from command line an input as:

application --fields 1-6,8

我需要按照用户在命令行上的要求显示字段.

I am required to display the fields as requested by the user on command line.

我想用.."代替-",这样我就可以将它们存储在数组中,例如

I thought of substituting '-' with '..' so that I can store them in array e.g.

$str = "1..15,16" ;
@arr2 = ( $str ) ;
@arr = ( 1..15,16 ) ;
print "@arr\n" ;
print "@arr2\n" ;

这里的问题是@arr 工作正常(应该如此),但在@arr2 中,整个字符串没有扩展为数组元素.

The problem here is that @arr works fine ( as it should ) but in @arr2 the entire string is not expanded as array elements.

我尝试过使用转义序列,但没有成功.

I have tried using escape sequences but no luck.

可以这样吗?

推荐答案

如果这是用户输入,如果您有任何安全问题,请不要对其使用字符串 eval.

If this is user input, don't use string eval on it if you have any security concerns at all.

尝试使用 Number::Range 代替:

 use Number::Range;

 $str = "1..15,16" ;
 @arr2 = Number::Range->new( $str )->range;
 print for @arr2;

为避免在无效范围内死亡,请执行以下操作:

To avoid dying on an invalid range, do:

 eval { @arr2 = Number::Range->new( $str )->range; 1 } or your_error_handling

还有 Set::IntSpan,它使用 - 而不是 ..:

There's also Set::IntSpan, which uses - instead of ..:

 use Set::IntSpan;

 $str = "1-15,16";
 @arr2 = Set::IntSpan->new( $str )->elements;

但它要求范围有序且不重叠(它是为在 .newsrc 文件上使用而编写的,如果有人记得那些是什么的话).它还允许无限范围(字符串以 -number 开始或以 number- 结尾),元素方法将在此范围内发出声音.

but it requires the ranges to be in order and non-overlapping (it was written for use on .newsrc files, if anyone remembers what those are). It also allows infinite ranges (where the string starts -number or ends number-), which the elements method will croak on.

这篇关于如何展开像“1..15,16"这样的字符串?变成数字列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆