my %exeDll; for ( @exeDllLines ) { chomp; my @a = grep /\S/, split /,/; # split on comma; filter out empty fields my @dlls = grep /\.dll$/, @a; # get list of dll files for my $exe ( grep /\.exe$/, @a ) { @{$exeDll{$exe}}{@dlls} = () # OR: $exeDll{$exe}{$_}++ for @dlls; } } # then you can iterate over the collected data: for my $exe ( sort keys %exeDll ) { print "$exe uses the following DLLs:\n"; for my $dll ( sort keys %{ $exeDll{$exe} } ) { print "\t$dll\n"; } }