Name^Code^Count Name1^0029^1 Name1^0038^1 Name1^0053^1 Name2^0013^3 Name2^0018^3 Name2^0023^5 Name2^0025^1 Name2^0029^1 Name2^0038^1 Name2^0053^1 Name3^0018^1 Name3^0060^1 Name4^0018^2 Name4^0025^5 Name5^0018^2 Name5^0025^1 Name5^0060^1 #### Name^0013^0018^0023^0025^0029^0038^0053^0060 Name1^^^^^1^1^1^ Name2^3^3^5^1^1^1^1^ Name3^^1^^^^^^1 Name4^^2^^5^^^^ Name5^^2^^1^^^^1 #### use strict; use warnings; my $map; my $sep = '^'; my @flds; my %codes; # Loop through the lines and create hashmap while (my $line = ) { chomp $line; @flds = split ('\^', $line); next unless $.>1; $map->{$flds[0]}->{$flds[1]} = $flds[2] or next; $codes{$flds[1]}++; } # Print the header line print "Name"; foreach my $k (sort keys %codes){ print "$sep" . "$k"; } print "\n"; # Iterate through the hash foreach my $k1 (sort keys %$map) { print $k1; foreach my $k2 (sort keys %codes) { print "$sep" and next unless defined $map->{$k1}->{$k2}; print "$sep" . "$map->{$k1}->{$k2}"; } print "\n"; } __DATA__ Name^Code^Count Name1^0029^1 Name1^0038^1 Name1^0053^1 Name2^0013^3 Name2^0018^3 Name2^0023^5 Name2^0025^1 Name2^0029^1 Name2^0038^1 Name2^0053^1 Name3^0018^1 Name3^0060^1 Name4^0018^2 Name4^0025^5 Name5^0018^2 Name5^0025^1 Name5^0060^1 #### print "$sep" and next unless defined $map->{$k1}->{$k2}; print "$sep" . "$map->{$k1}->{$k2}"; #### printf "%s%s", FS, map[name[i],value[j]] #### $codes{$flds[1]}++