合并连续的数字范围

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

Combine consecutive number range

问题

  1. 我想要在Perl中合并连续的数字范围[`Number::Range`](https://metacpan.org/pod/Number::Range) 没有达到我的预期
  2. ```perl
  3. use Data::Dumper;
  4. use Number::Range;
  5. say STDERR Dumper(Number::Range->new("1000..5555,5559..9999,5556..5557,5558")->rangeList);

结果为:

  1. $VAR1 = [
  2. 5556,
  3. 5558
  4. ];
  5. $VAR2 = [
  6. 5559,
  7. 9999
  8. ];
  9. $VAR3 = [
  10. 1000,
  11. 5555
  12. ];

我预期的是:

  1. $VAR1 = [
  2. 1000,
  3. 9999
  4. ];
英文:

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

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

results in:

  1. $VAR1 = [
  2. 5556,
  3. 5558
  4. ];
  5. $VAR2 = [
  6. 5559,
  7. 9999
  8. ];
  9. $VAR3 = [
  10. 1000,
  11. 5555
  12. ];

I expected:

  1. $VAR1 = [
  2. 1000,
  3. 9999
  4. ];

答案1

得分: 2

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

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

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

输出结果:

  1. 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:

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

Prints:

  1. 1000..9999

答案2

得分: 2

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

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

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

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

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

它们会被排序。

英文:

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

  1. 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)

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

Returns them sorted.

答案3

得分: 0

使用替代模块 Set::IntSpan

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

Using an alternative module Set::IntSpan:

  1. use Set::IntSpan::Fast::XS qw();
  2. 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:

确定