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

查看:14
本文介绍了如何扩展像“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
" ;
print "@arr2
" ;

这里的问题是 @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-),elements 方法将在此范围内发声.

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天全站免登陆