合并连续的数字范围

huangapple go评论60阅读模式
英文:

Combine consecutive number range

问题

我想要在Perl中合并连续的数字范围[`Number::Range`](https://metacpan.org/pod/Number::Range) 没有达到我的预期

```perl
use Data::Dumper;
use Number::Range;

say STDERR Dumper(Number::Range->new("1000..5555,5559..9999,5556..5557,5558")->rangeList);

结果为:

$VAR1 = [
          5556,
          5558
        ];
$VAR2 = [
          5559,
          9999
        ];
$VAR3 = [
          1000,
          5555
        ];

我预期的是:

$VAR1 = [
          1000,
          9999
        ];
英文:

I would like to combine consecutive number ranges in Perl. Number::Range didn't do what I expected:

use Data::Dumper;
use Number::Range;

say STDERR Dumper(Number::Range->new("1000..5555,5559..9999,5556..5557,5558")->rangeList);

results in:

$VAR1 = [
          5556,
          5558
        ];
$VAR2 = [
          5559,
          9999
        ];
$VAR3 = [
          1000,
          5555
        ];

I expected:

$VAR1 = [
          1000,
          9999
        ];

答案1

得分: 2

显然,该模块在内部以这种方式表示数据。它似乎不会创建一个合并的数组集合,正如您所希望的那样。

如果您在标量上下文中使用 range 方法,您将看到一个合并的范围字符串:

use Number::Range;
my $range = Number::Range->new("1000..5555,5559..9999,5556..5557,5558");
my $format = $range->range();
print "$format\n";

输出结果:

1000..9999
英文:

Apparently, the module represents the data that way internally. It does not seem to create a merged set of arrays as you had hoped.

If you use the range method in scalar context, you will see a single merged range string:

use Number::Range;
my $range = Number::Range->new("1000..5555,5559..9999,5556..5557,5558");
my $format = $range->range();
print "$format\n";

Prints:

1000..9999

答案2

得分: 2

该模块的方法 range 会按照你所期望的,在列表上下文中返回范围。

say for Number::Range->new("10..12,4,15..18")->range;

每行打印一个数字,按顺序排列。在标量上下文中返回一个字符串,也是按顺序排列的。

或者,你可以使用列表/数组来构建一个对象(未记录在文档中)。

my @nums = Number::Range->new(10..12,4,15..18)->range;
say for @nums;

它们会被排序。

英文:

The module's method range returns the range as a list as you'd expect, in list context

say for Number::Range->new("10..12,4,15..18")->range;

prints a number per line, sorted. Returns a string in a scalar context, also sorted.

Or, you can construct an object with a list/array (undocumented)

my @nums = Number::Range->new(10..12,4,15..18)->range;
say for @nums;

Returns them sorted.

答案3

得分: 0

使用替代模块 Set::IntSpan

use Set::IntSpan::Fast::XS qw();
say STDERR Set::IntSpan::Fast::XS->new(1000..5555,5559..9999,5556..5557,5558)->as_string;
英文:

Using an alternative module Set::IntSpan:

use Set::IntSpan::Fast::XS qw();
say STDERR Set::IntSpan::Fast::XS->new(1000..5555,5559..9999,5556..5557,5558)->as_string;

huangapple
  • 本文由 发表于 2023年7月10日 21:56:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76654474.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定