2

我有一个带有数字的文本文件,我将其分组如下,用空行分隔:

42.034 41.630 40.158 26.823 26.366 25.289 23.949

34.712 35.133 35.185 35.577 28.463 28.412 30.831

33.490 33.839 32.059 32.072 33.425 33.349 34.709

12.596 13.332 12.810 13.329 13.329 13.569 11.418

注意:组的长度总是相等的,并且可以排列成多于一行,如果组很大,比如说 500 个数字。我正在考虑将这些组放在数组中并沿文件的长度进行迭代。

我的第一个问题是:我应该如何从数组 1 中减去数组 2 的第一个元素,从数组 2 中减去数组 3,第二个元素也是如此,依此类推直到组结束?

IE:

34.712-42.034,35.133-41.630,35.185-40.158 ...till the end of each group

33.490-34.712,33.839-35.133   ..................

然后保存一组中第一个元素的差异(第二个问题:如何?)直到最后

IE:

34.712-42.034 ; 33.490-34.712 ; and so on in one group

35.133-41.630 ; 33.839-35.133 ; ........

我是初学者,所以任何建议都会有所帮助。

4

2 回答 2

6

假设您打开了文件,以下是一个快速草图

use List::MoreUtils qw<pairwise>;
...

my @list1 = split ' ', <$file_handle>;
my @list2 = split ' ', <$file_handle>;

my @diff  = pairwise { $a - $b } @list1, @list2;

pairwise是最简单的方法。

否则有旧的备用:

# construct a list using each index in @list1 ( 0..$#list1 )
# consisting of the difference at each slot.
my @diff = map { $list1[$_] - $list2[$_] } 0..$#list1;
于 2011-03-01T15:24:46.420 回答
0

这是使 Axeman 的代码工作的其余基础设施:

#!/usr/bin/perl
use strict;
use warnings;
use List::MoreUtils qw<pairwise>;

my (@prev_line, @this_line, @diff);
while (<>) {
    next if /^\s+$/; # skip leading blank lines, if any
    @prev_line = split;
    last;
}

# get the rest of the lines, calculating and printing the difference,
# then saving this line's values in the previous line's values for the next
# set of differences
while (<>) {
    next if /^\s+$/; # skip embedded blank lines

    @this_line = split;
    @diff      = pairwise { $a - $b } @this_line, @prev_line;

    print join(" ; ", @diff), "\n\n";

    @prev_line = @this_line;
}

所以给定输入:

1 1 1

3 2 1

2 2 2

你会得到:

2 ; 1 ; 0

-1 ; 0 ; 1
于 2011-04-06T01:52:29.957 回答