I'd like to convert a sting of the form 1,2,25-27,4,8,14,7-10
into a list of the actual values: 1,2,4,7,8,9,10,14,25,26,27
.
I've searched and found nothing that does this sort of expansion. Anyone aware of way to do this easily?
I'd like to convert a sting of the form 1,2,25-27,4,8,14,7-10
into a list of the actual values: 1,2,4,7,8,9,10,14,25,26,27
.
I've searched and found nothing that does this sort of expansion. Anyone aware of way to do this easily?
my $s = "1,2,25-27,4,8,14,7-10";
my %seen;
my @arr =
sort { $a <=> $b }
grep { !$seen{$_}++ }
map {
my @r = split /-/;
@r>1 ? ($r[0] .. $r[1]) : @r;
}
split /,/, $s;
print "@arr\n";
输出
1 2 4 7 8 9 10 14 25 26 27
另一种快速完成此操作的方法是使用eval的字符串版本。但是您必须记住,使用 eval 有一些安全隐患,因此您最好在将任何字符串传递给 eval 之前对其进行清理。
use strict;
use warnings;
my $string = "1,2,25-27,4,8,14,7-10";
$string =~ s/-/../g;
my @list = sort {$a <=> $b} keys { map {$_, 1} eval $string };
print "@list\n";
#output
1 2 4 7 8 9 10 14 25 26 27