首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >垂直索引Perl

垂直索引Perl
EN

Stack Overflow用户
提问于 2013-02-22 18:24:12
回答 2查看 82关注 0票数 0

文件1的范围为3-9、2-6等

代码语言:javascript
运行
复制
3 9
2 6
12 20

File2具有值:列1指示范围,列2具有值。

代码语言:javascript
运行
复制
1   4
2   4
3   5
4   4
5   4
6   1
7   1
8   1
9   4

我想计算以file1为单位的范围的值(file2,column2)之和。例如:如果范围是3-9,则值的和将是5+4+4+1+1+1+4 = 20

我试过的是:

代码语言:javascript
运行
复制
open (FILE1,"file1.txt");
open (FILE2,"file2.txt");

@file1 = <FILE1>;
@file2 = <FILE2>;

foreach (@file1)
    {
        @split_file2 = split("\\s",$_); //splitting the file by space


foreach (@file2)
    {
        @split_file2 = split("\\s",$_);  //splitting the file by space


if (@split_file1[0] == @split_file2[0]) //if column0 of file1 matches with column0 of file2
    {
        $x += @split_file2[1];  //sum the column1 of file2 

       if ( @split_file2[0] == @split_file1[0] ) //until column1 of file1 = column0 of file2.

            {
            last;
            }
    }
}}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-22 19:06:52

另一种解决方案:

代码语言:javascript
运行
复制
#!/usr/bin/perl

use strict;
use warnings;

my $f1 = shift;
my $f2 = shift;
open FH1, "<", $f1 or die "$!\n";
open FH2, "<", $f2 or die "$!\n";

my %data;

while (<FH1>) {
    $data{$1} = $2 if ($_ =~ m/^(\d+)\s+(\d+)$/);
}

while (<FH2>) {
    if ($_ =~ m/^(\d+)\s+(\d+)$/) {
        my $sum;
        for ($1..$2) {
            $sum += $data{$_} if defined($data{$_});
        }
        print "sum for $1-$2: $sum\n" if defined($sum);
    }
}

close FH1;
close FH2;

联系方式:script.pl values.txt ranges.txt

票数 0
EN

Stack Overflow用户

发布于 2013-02-22 18:51:39

  • Always use use strict; use warnings;.
  • split /\s/更易于阅读。

代码语言:javascript
运行
复制
use strict;
use warnings;
use feature qw( say );

use List::Util qw( sum );

my $file1 = 'file1.txt';
my $file2 = 'file2.txt';

my @file2;
{    
   open(my $fh, '<', $file2)
      or die "Can't open $file2: $!\n";
   while (<$fh>) {
      my ($k, $v) = split;
      $file2[$k] = $v;
   }
}

{    
   open(my $fh, '<', $file1)
      or die "Can't open $file1: $!\n";
   while (<$fh>) {
      my ($start, $end) = split;
      say sum grep defined, @file2[$start .. $end];
   }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15021898

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档