#! perl use strict; use warnings; my @ComplicationsSurgicalProcedMedCare_238 = (27661, 27783, 27788, 2853, 28741); my @SuperficialInjuryContusion_239 = ( 9062, 9063, 9100, 9101); my ($infile, $outfile) = ('2009.txt', 'Output by RID.txt'); my %DiagNames = ( 238 => 'Complications of surgical procedures or medical care', 239 => 'Superficial injury; contusion', ); my %DiagCodes; $DiagCodes{$_} = 238 for @ComplicationsSurgicalProcedMedCare_238; $DiagCodes{$_} = 239 for @SuperficialInjuryContusion_239; my %Diags; open my $fh, '<', $infile or die "Can't open file '$infile' for reading: $!"; while (<$fh>) { my ($RID, $DiagCode) = split; ++$Diags{$RID}{$DiagCode}; } close $fh or die "Can't close file '$infile': $!"; open my $fh1, '>', $outfile or die "Cannot open file '$outfile' for writing: $!"; for my $key (sort keys %Diags) { print $fh1 "$key\n{\n"; for (sort { $a <=> $b } keys %{ $Diags{$key} } ) { if (exists $DiagCodes{$_}) { printf $fh1 " %s: %d, %d\n", $DiagNames{ $DiagCodes{$_} }, $_, $Diags{$key}->{$_}; } else { printf $fh1 " Unrecognized code: %d\n", $_; } } print $fh1 "}\n\n"; } close $fh1 or die "Can't close file '$outfile': $!"; #### Tom_Jones 9062 John_Smith 27783 Tom_Jones 9062 Jane_Brown 9100 Tom_Jones 28741 John_Smith 9062 Tom_Jones 9062 Jane_Brown 9062 Tom_Jones 28741 Jane_Brown 2853 Jane_Brown 9062 Tom_Jones 12345 #### Jane_Brown { Complications of surgical procedures or medical care: 2853, 1 Superficial injury; contusion: 9062, 2 Superficial injury; contusion: 9100, 1 } John_Smith { Superficial injury; contusion: 9062, 1 Complications of surgical procedures or medical care: 27783, 1 } Tom_Jones { Superficial injury; contusion: 9062, 3 Unrecognized code: 12345 Complications of surgical procedures or medical care: 28741, 2 }