1,
2,
3,
####
1,10,20,30,40,
1,15,25,35,45,
2,3,5,6,7,8,
3,100,200,300,400
2,10,4,-8,16,32
3,300,400,500,600
####
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Text::CSV;
use List::Util qw 'sum';
my @IDs;
my $IDfile = 'ids.csv';
my $Intfile = 'interactions.csv';
my $csv = Text::CSV->new() or die "Can't use CSV: " . Text::CSV->error_diag();
# Open file containing IDs
# our example has id's in the first column
my $fh;
open( $fh, '<', $IDfile ) or die "Can't open $IDfile: $!";
# build an array of IDs for processing;
while ( my $row = $csv->getline( $fh ) ){
push @IDs, $row->[0];
}
# close csv
$csv->eof or $csv->error_diag();
close $fh;
# parse interactions
open ( $fh, '<', $Intfile ) or die "Can't open $Intfile: $!";
my $data = $csv->getline_all($fh);
$csv->eof or $csv->error_diag();
close $fh;
# for each ID in our array
foreach my $ID ( @IDs ){
my @total;
# loop through interactions data
foreach my $row ( @$data ){
# if the fist column is equal to the value of $ID
if ( $row->[0] == $ID ){
# add the value of the fourth column to the array
push @total, $row->[3];
}
}
# display totals
say "Total for ID $ID: " . sum( @total ) if ( @total );
}
####
Total for ID 1: 65
Total for ID 2: -2
Total for ID 3: 800