use strict; use warnings; # Create a test file open outFile, ">", "file1.txt"; print outFile <; close inFile; my %animals; # build a hash keyed by animal with the count as value map {/(\w+)\s+(\d+)/; $animals{$1}=$2} @lines; # Production code would use file2 rather than DATA while () { /(\w+)/; #Assume animal is always the first thing on the line # Bump animal count - creates new entry if new animal ++$animals{$1} if defined $1; } open outFile, ">", "file1.txt"; for (@lines) { /(\w+)/; printf outFile "%-6s %d\n", $1, $animals{$1}; $animals{$1} = 0; # Tag as printed } #add any new animals to the end of the file for (keys %animals) { next if ! $animals{$_}; printf outFile "%-6s %d\n", $_, $animals{$_}; } close outFile; __DATA__ rabbit feed 10kg used on 21/10/2005 by consumer1 cow feed 100kg used on 11/11/2005 by consumer1 sheep feed 50kg used on 24/11/2005 by consumer3 #### rabbit 2 hen 0 pig 2 cow 3 sheep 6