How to subtract values ​​in 2 different arrays in perl?

Hi I have two arrays containing 4 columns and I want to subtract the value in column 1 of array2 from the value in column 1 of array1 and the value of column2 of array2 from column2 of array1 and so on. Example:

my @array1=(4.3,0.2,7,2.2,0.2,2.4)
my @array2=(2.2,0.6,5,2.1,1.3,3.2)

therefore the required output

2.1 -0.4 2     # [4.3-2.2] [0.2-0.6] [7-5]
0.1 -1.1 -0.8  # [2.2-2.1] [0.2-1.3] [2.4-3.2]

The code is used for this.

my @diff = map {$array1[$_] - $array2[$_]} (0..2);          
print OUT join(' ', @diff), "\n";

and the result that I get now is

2.1 -0.4 2
2.2 -1.1 3.8

Again, the first line is used from the first, not the second row, how can I solve this problem?

I need to output rows of 3 columns as shown above, so I filled my array in a row of three values.

+5
source share
2 answers

, . Perl - qw(), . , .

Perl 2D . 2.2 1 1 @array1 - it 3 @array1. Perl, - , , 1- , .

( 6 2 3 ), arrayrefs ( Perl C):

my @array1=( [ 4.3, 0.2, 7 ],
             [ 2.2, 0.2, 2.4] );


for(my $idx=0; $idx1 < 2; $idx1++) {
    for(my $idx2=0; $idx2 < 3; $idx2++) {
        print $array1[$idx1]->[$idx2] - $array2[$idx1]->[$idx2];
        print " ";
    }
    print "\n";
}

, , C:

my @array1=( 4.3, 0.2, 7,      # index 0..2
             2.2, 0.2, 2.4);   # index 3..5


for(my $idx=0; $idx1 < 2; $idx1++) {
    for(my $idx2=0; $idx2 < 3; $idx2++) {
        print $array1[$idx1 * 3 + $idx2] - $array2[$idx1 * 3 + $idx2];
        print " ";
    }
    print "\n";
}
+4

. , ( ), , .

use strict;
use warnings;

my @a1 = (4.3,0.2,7,2.2,0.2,2.4);
my @a2 = (2.2,0.6,5,2.1,1.3,3.2);
my @out = map { $a1[$_] - $a2[$_] } 0 .. $#a1;

print "@out[0..2]\n";
print "@out[3..$#a1]\n";
+5

All Articles