2010-11-22 8 views
1

다음 형식의 csv 파일 (매우 큰 파일)이 있습니다.perl은 CSV 파일의 열 차이를 계산합니다.

key1,val1,val2,val3... ,valn 
key2,val2,val5,val1....,valn 
... 
... 
keyn,val7,val9,val11....,valn 
key1,val2,val4,val8.....,valn 
key2,val10,val12,val14..., valn 
... 
... 
keyn,val2,val4,val8.....,valn 
key1,val3,val5,val7... ,valn 
key2,val0,val9,val3....,valn 

key1과 keyn (및 값)은 csv 파일에서 여러 번 반복됩니다.

값 (val1, valn)은 double (float)입니다.

1) 파일의 시작 부분에서 난 키의 다음 발생에 열 값 (을 val2, val4 예 val6) 사이의 차이를 계산하려는 각 키 : 사용자가 인쇄하고 싶은

.

그래서 예를

내가

키 1을 인쇄 할

key1,2,4,6 
key2,3,5,7 
... 
... 
key1,4,6,8 
key2,4,6,8 

을 위해 : 이전 기록에서 DIFF가 key2,1,1입니다 : 이전의 기록에서 DIFF는 키 2가 key1,2,2,2입니다 1 ..

keyn : 이전의 기록에서 DIFF는

2

)이 O를 각 연속 발생을 반복적으로이 작업을 수행 ...........입니다 각 키. 여기

내가 (해시의 저장 값)에 와서 무엇

#!/usr/bin/perl 

my %hash; 
open my $fh, '<', 'file1.csv' or die "Cannot open: $!"; 
while (my $line = <$fh>) { 
    $line =~ s/\s*\z//; 
    my @array = split /,/, $line; 
    my $key = shift @array; 
    $hash{$key} = \@array; 
} 
close $fh; 
+0

죄송합니다 ... 나쁜 이드 - :) 그것은 빠른 게시물이었습니다. ... 나는 유효한 이메일 주소가 있습니다 –

+0

@mystery_man 나는 당신이 좋은 회사에 있다고 생각합니다. http://en.wikipedia.org/wiki/Austin_Powers:_International_Man_of_Mystery 더 중요한 것은, 당신은 당신의 문제를 잘 설명하지 않았다는 것입니다. –

+0

익숙한 느낌입니다. 숙제? –

답변

0

내 시도 :

use strict; 
use warnings; 

use Text::CSV_XS; 

use Math::Matrix; 



my $csv = Text::CSV_XS->new({binary => 1}); 

my %hash; 

my @results; 

open my $fh, '<', 'file1.csv' or die "Cannot open: $!"; 

while (my $line = <$fh>) { 

    if ($csv->parse($line)) { 

    my @array = $csv->fields; 
    my $key = shift @array; 

    if (! exists $hash{$key}) { 
     $hash{$key} = \@array; 
     next; 
    } 



    my $previous_record = Math::Matrix->new($hash{$key}); 
    my $current_record = Math::Matrix->new(\@array); 

    my $new_record = $previous_record->add($current_record->negative); 

    push @results, @$new_record; 

    $hash{$key} = \@array; 



    } 
    else { 
    my $err = $csv->error_input; 
    print "error parsing: $err\n"; 
    } 

} 
+0

이것은 또한 효과가 있습니다. 그러나 이전 기록과 현재 기록의 차이를 계산했습니다. 나는 내가 문제를 더 정확하게 설명하지 않았다고 생각한다. 노력해 주셔서 대단히 감사합니다. –

2

당신은 일을 시도 할 수 있습니다 :

# get the key. 
    my $key = shift @array; 

    # see if the key is already seen. 
    if(exists $hash{$key}) { 
      # get ref to previous record of this key. 
      my $ref = $hash{$key}; 

      # print key. 
      print "$key,"; 

      # a new array. 
      my @new_array; 

      # populate the new array. 
      for(my $i=0;$i<=$#array;$i++) { 
        $new_array[$i] = $array[$i] - $$ref[$i]; 
      } 

      # join the array elements with comma. 
      print join",",@new_array; 
      print "\n"; 
    } 

    # add/replace the current array as value for the current key. 
    $hash{$key} = \@array; 

You can see the working code here

+0

대단히 고마워요, codaddict. 이것은 첫 번째 키를 제외하고는 완벽하게 작동했습니다. –

관련 문제