user831579
user831579

Reputation: 1031

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 column1 of array2 from value in column1 of array1 and value of column2 of array2 from column2 of array1 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)

so the required output is

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]

For this the code I used is

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

and the output I am getting now is

2.1 -0.4 2
2.2 -1.1 3.8

Again the first row is used from array one and not the second row, how can I overcome this problem?

I need output in rows of 3 columns like the way i have shown above so just i had filled in my array in row of 3 values.

Upvotes: 5

Views: 3259

Answers (2)

TLP
TLP

Reputation: 67900

This will produce the requested output. However, I suspect (based on your comments), that we could produce a better solution if you simply showed your raw input.

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";

Upvotes: 5

DVK
DVK

Reputation: 129481

First of all, your code doesn't even compile. Perl arrays aren't space separated - you need a qw() to turn those into arrays. Not sure how you got your results.

Perl doesn't have 2D arrays. 2.2 is NOT a column1 of row 1 of @array1 - it's element with index 3 of @array1. As far as Perl is concerned, your newline is just another whitespace separator, NOT something that magically turns a 1-d array into a table as you seem to think.

To get the result you want (process those 6 elements as 2 3-element arrays), you can either store them in an array of arrayrefs (Perl's implementation of C multidimentional arrays):

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

or, you can simply fake it by using offsets, the same way pointer arithmetic works in C's multidimentional arrays:

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

Upvotes: 4

Related Questions