#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11147822 use warnings; use Path::Tiny; path("/tmp/11147822.$_.txt")->spew( < =~ /^(\w+)\s+(\d+)/ or die; my ($name, $value) = ($1, $2); while( <$fh> ) { if( /^(\w+)\s+(\d+)/ ) { if( $1 eq $name ) { $value += $2; } else { print $tosort "$name\t$value\n"; ($name, $value) = ($1, $2); } } } print $tosort "$name\t$value\n"; # be sure to print last one close $tosort or die; #### blah 2300 word 2700 bar 3500 foo 7300