""Chris Charley""  wrote in message

"Chris Stinemetz"  wrote in message news

Hello List,

I have input data such as far below:

I would like to read the data into an array and modify the 2nd index if the
0th and first indices are identical.
I would like the updated 2nd index to be an average of the 2nd index where
both occurences of 0th and 1st indices match.

[snip question]


Hi Chris,

[snip verbose answer]

I engaged fingers before my brain.  :-(

No need to make 2 passes to solve this problem. A one pass solution proved to be more concise and conserved resources (compared to the 2 pass solution).

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw/ sum /;

my %data;

my ($col0, $col1, @rest) = split ' ', <DATA>;
push @{ $data{$col0, $col1} }, \@rest;

while (<DATA>) {
   my ($col0, $col1, @rest) = split;
   my $key = "$col0$;$col1";

   if (exists $data{$key}) {
       push @{ $data{$key} }, \@rest;
   }
   else {
       print_it(%data);

       undef %data;
       push @{ $data{$key} }, \@rest;
   }

}

print_it(%data);

sub print_it {
   my ($comp_key, $aref) = @_;

   my $avg  = sprintf "%.f", sum( map $_->[0], @$aref ) / @$aref;

   my ($col0, $col1) = split /$;/, $comp_key;

   for my $i (0 .. $#$aref) {
       print join(" ", $col0, $col1, $avg, $aref->[$i][1]), "\n";
   }
}

__DATA__
22 1 60 65
22 2 180 90
22 3 300 90
23 1 0 65
23 2 90 65
23 3 260 65
24 1 60 65
24 1 40 65
24 2 180 65
24 2 160 65
. . . .

Chris

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to