How about this? (works for me with test data)
use strict;
use warnings;
my %code_to_full;
my %field_by_code;
open my $f, '<', 'test.txt' or die "open: $!";
my $last_code;
while (<$f>) {
my ($code, $full) = /^([A-Z]{2}):\s+(.+)/i;
if ($code && $full) {
$code_to_full{$code} = $full;
$field_by_code{$code} = '';
$last_code = $code;
}
else {
unless ($last_code) {
warn "No code and last_code blank; this shouldn't happen";
}
$field_by_code{$last_code} .= $_;
}
}
for (sort keys %code_to_full) {
print "Code: $_\n";
print "Full: $code_to_full{$_}\n";
print "Field data: $field_by_code{$_}\n\n";
}
Things I'd like to point out:
- use of strict
- lexical filehandles
- error checking on system call (open)
"Half of all adults in the United States say they have registered as an organ donor, although only some have purchased a motorcycle to show that they're really serious about it."
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.