根据值的相似性分隔和输出数值。

时间:2013-03-18 14:19:26

标签: perl

我认为perl可以做到这一点,但我对perl很新 希望有人可以帮助我。 我有这样的文件(实际文件超过一万行,值按升序排列,一些值重复)。


1

2

2

35

45


我想根据值的相似性将这些行分成单独的文件(例如,值的差值小于30)。

outfile1


1

2

2


outfile2


35

45


谢谢

2 个答案:

答案 0 :(得分:1)

这非常简单,只需在每次必要时打开一个新文件,即第一行数据,然后每次有30或更多的间隙。

此程序需要输入文件的名称作为命令行上的参数。

use strict;
use warnings;
use autodie;

my ($last, $fileno, $fh);

while (<>) {
  my ($this) = /(\d+)/;
  unless (defined $last and $this < $last + 30) {
    open $fh, '>', 'outfile'.++$fileno;
  }
  print $fh $_;
  $last = $this;
}

答案 1 :(得分:0)

这应该很容易。只需记住变量中的前一个值,就可以看出差异是否足够大。您还必须计算到目前为止创建的输出文件,以便在需要时命名新文件。

#!/usr/bin/perl
use warnings;
use strict;

my $threshold = 30;

my $previous;
my $count_out = 0;
my $OUTPUT;
while (<>) {
    if (not defined $previous or $_ > $previous + $threshold) {
        open $OUTPUT, '>', "outfile" . $count_out++ or die $!;
    }
    print $OUTPUT $_;
    $previous = $_;
}
相关问题