lorenz has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks, I have a problem here, and I want to use perl to automate this reocurring calculation: I have files with values organized in 8 rows and 12 columns (space separated) and I want to create a new file showing the differences of the corresponding values (e.g. value row1,col1 in file1 - value row1,col1 in file2) in the same 12x8 pattern. Could you give me ideas for tackling this problem? cheers, Lorenz

Replies are listed 'Best First'.
Re: Subtracting values in two files
by TomDLux (Vicar) on May 23, 2011 at 13:51 UTC
    use autodie; open my $in1, '<', $file1; open my $in2, '<', $file2; open my $out, '>', $file3; for my $row ( 0..7 ) { my $line1 = <$in1>; chomp $line1; my @line1 = split / /, $line1; my $line2 = <$in2>; chomp $line2; my @line2 = split / /, $line2; my @out; for my $col ( 0..11 ) { push @out, $line1[$col] - $line2[$col]; } say { $out } join ' ', @out }

    Since I want to use $col to index the line component arrays, it needs to be zero based. For symmetry, $row should also be zero-based. Otherwise, I would use 1..8 and 1..12, for clarity.

    As Occam said: Entia non sunt multiplicanda praeter necessitatem.

Re: Subtracting values in two files
by CountZero (Bishop) on May 23, 2011 at 17:15 UTC
    I tried the following:
    use Modern::Perl; use List::MoreUtils qw/pairwise/; use autodie; open my $in1, './file1.dat'; open my $in2, './file2.dat'; while (my $first = <$in1> and my $second = <$in2>) { my @first = split / /, $first; my @second = split / /, $second; my @result = pairwise {$a - $b} @first, @second; say "@result"; }

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      just great! Thank you all! L
Re: Subtracting values in two files
by wind (Priest) on May 23, 2011 at 15:38 UTC

    TomDLux's solution totally works, but the below code makes fewer assumptions concerning the nature of the data:

    use autodie; use List::Util qw(max); use strict; use warnings; open my $in1, $file1; open my $in2, $file2; open my $out, '>', $file3; while (! eof($in1) && ! eof($in2)) { chomp(my $line1 = <$in1>); chomp(my $line2 = <$in2>); my @line1 = split ' ', $line1; my @line2 = split ' ', $line2; my @out = map {$line1[$_] - $line2[$_]} (0..max($#line1,$#line2)); print $out join(' ', @out), "\n"; } warn "Premature end of file: $file1" if ! eof($in2); warn "Premature end of file: $file2" if ! eof($in1);