Here is how I would do it. Note I'd class this as fairly advanced perl - hash refs, array refs all nested etc, but an idiom well worth picking up.
#!/usr/bin/perl -w
use strict;
my ($key);
# Collect the data
my $data = {};
while (<>)
{
chomp;
my @row = split /,/;
next unless @row;
$key = shift @row;
# the following is the most important line in the program
# understand it and you've got it!
push @{$data->{$key}}, [ @row ];
}
# Uncomment these lines if you have Data::Dumper and you want to see
# what the data structure looks like
# use Data::Dumper;
# $Data::Dumper::Terse = 1;
# print Dumper($data);
print "Total count\n";
for $key (sort keys %$data)
{
print " $key has ", scalar @{$data->{$key}} , " entries\n";
}
print "Second and third items of all QTYs\n";
for $key (@{$data->{QTY}})
{
print " $key->[0], $key->[1]\n";
}
print "Third items in HDRs\n";
for $key (@{$data->{HDR}})
{
print " $key->[1]\n";
}
print "4th and 5th items in OTIs\n";
for $key (@{$data->{OTI}})
{
print " $key->[2], $key->[3]\n";
}
Run this with
perl progname.pl 824.txt
When I run it on your test data it produces this output
Total count
AMT has 3 entries
BGN has 1 entries
HDR has 1 entries
OTI has 2 entries
QTY has 4 entries
TED has 2 entries
Second and third items of all QTYs
46, 10
53, 0
54, 10
55, 0
Third items in HDRs
200008081441EST
4th and 5th items in OTIs
WEDI620000802, 159
0021000095, 159