在Perl中,如何从连字符/逗号字符串生成数字列表,如: 1-8,10,12-15,23 ? 预期产出为: [1,2,3,4,5,6,7,8,10,12,13,14,15,23]
好的,我有一些似乎有效的解决方案,我能优化吗? :
@cl_list = "0,2-7,13-16"
@cl_list = split(/,/,join(',',@cl_list));
foreach $cl (@cl_list){
if (index($cl, '-') != -1){
@range=split(/-|,/,$cl,2);
$ld=$range[0];
$ud=$range[1];
while ($ld <= $ud) {
push @list, $ld;
print "$ld\n";
$ld++;
}
}
else {
push @list, $ld;
}
}
print "list=@list\n";
答案 0 :(得分:2)
我可能会这样做:
#!/usr/bin/env perl
use strict;
use warnings;
my $thing = '1-8,10,12-15,23';
my @values;
#split the string on commas.
for ( split /,/, $thing ) {
#split each element in `-`. ($end is undefined if no `-` present)
my ( $start, $end ) = split ( '-' );
#iterate from start to end (or start to start if end is undef)
push ( @values, $_ ) for ( $start .. $end // $start );
}
print join ",", @values;
打印:
1,2,3,4,5,6,7,8,10,12,13,14,15,23
答案 1 :(得分:0)
这是固定的Sobrique解决方案:
use strict;
use warnings;
my $thing = '1-8,10,12-15,23';
my @values;
#split the string on commas.
for ( split /,/, $thing ) {
#split each element in `-`. ($end is undefined if no `-` present)
my ( $start, $end ) = split ( '-',$_ );
if (!defined $end) { $end=$start;}
#iterate from start to end (or start to start if end is undef)
push ( @values, $_ ) for ( $start..$end );
}
print join ",", @values;