0

ファイル 1 の範囲は 3 ~ 9、2 ~ 6 など

3 9
2 6
12 20

File2 には値があります。列 1 は範囲を示し、列 2 には値があります。

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 になります。

私が試したことは次のとおりです。

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;
            }
    }
}}
4

2 に答える 2

3
  • 常に使用しますuse strict; use warnings;
  • split /\s/読みやすくなっています。split ' 'あなたが実際に欲しいものです。
  • グローバル変数を使用しないでください (ファイル ハンドルなど)。
  • openを追加するだけで成功するかどうかを確認すると便利ですor die $!
  • file1と ではなく、意味のある名前を使用してくださいfile2

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];
   }
}
于 2013-02-22T10:51:39.490 に答える
0

別の解決策:

#!/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

于 2013-02-22T11:06:51.933 に答える