#!/usr/bin/perl use 5.010; use strict; use warnings; my %data; my %seen; while () { chomp; my ($id, $name, $type, $pid, $qty, $gross) = split /\s*,\s*/; given ($type) { when ('Item') { $data{$id,$name}{$type}{$pid}{qty} += $qty; $data{$id,$name}{$type}{$pid}{gross} += $gross; $seen{$pid} = 1; next; } when ('Cart') { $data{$id,$name}{$type}{qty} = $qty; $data{$id,$name}{$type}{gross} = $gross; } } } my @pids = sort keys %seen; print "Txn ID, Name, Qty, Gross"; print ", $_ Qty, $_ Gross" for @pids; print "\n"; foreach my $ckey (sort keys %data) { my ($id, $name) = split $;, $ckey; print "$id, $name, ", $data{$ckey}{Cart}{qty} // "", ", ", $data{$ckey}{Cart}{gross} // ""; foreach my $pid (@pids) { print ", ", $data{$ckey}{Item}{$pid}{qty} // "", ", ", $data{$ckey}{Item}{$pid}{gross} // ""; } print "\n"; } __DATA__ Txn ID, Name , Type , Product ID, Qty, Gross 010 , Moe , Cart , , 1 , 15 010 , Moe , Item , widget-1 , 1 , 15 020 , Larry, Cart , , 3 , 35 020 , Larry, Item , widget-1 , 1 , 15 020 , Larry, Item , widget-2 , 2 , 20 #### Txn ID, Name, Qty, Gross, widget-1 Qty, widget-1 Gross, widget-2 Qty, widget-2 Gross 010, Moe, 1, 15, 1, 15, , 020, Larry, 3, 35, 1, 15, 2, 20