use strict; use warnings; use 5.010; use Data::Dumper; open my $lookFH, q{<}, \ < ); my $lookForRE = do{ local $" = q{|}; qr{^(@lookFor)\s+(\d+)} }; my %accumulate; open my $nosFH, q{<}, \ < ) { next unless m{$lookForRE}; chomp; push @{ $accumulate{ $1 }->{ lines } }, $_; $accumulate{ $1 }->{ sum } += $2; } foreach my $group ( @lookFor ) { say join q{ }, $_, $accumulate{ $group }->{ sum } for @{ $accumulate{ $group }->{ lines } } } print Data::Dumper->Dumpxs( [ \ %accumulate ], [ qw{ *accumulate } ] ); #### 20 23424 332444 20 56756 332444 20 82757 332444 20 83758 332444 20 09347 332444 20 76402 332444 30 91857 364101 30 92785 364101 30 89275 364101 30 90184 364101 50 29349 184748 50 71674 184748 50 83725 184748 %accumulate = ( '50' => { 'lines' => [ '50 29349', '50 71674', '50 83725' ], 'sum' => '184748' }, '30' => { 'lines' => [ '30 91857', '30 92785', '30 89275', '30 90184' ], 'sum' => '364101' }, '20' => { 'lines' => [ '20 23424', '20 56756', '20 82757', '20 83758', '20 09347', '20 76402' ], 'sum' => '332444' } );