Sorry, but you can't consistently parse data that is THIS inconsistent. Blank lines are easy to ignore, but how can you ignore lines with "noise" at the start without a solid way to denote the start of your data?
Try your best to clean up the incoming data. Until then, here are some parsing tricks that might help you keep some of your code
maintainable (note I didn't say
fast).
my %KEY_PARSER = (
"number" => {
START_COMMAND => qr{number:\s*}i,
VALUE_MATCH => qr{\d+},
},
"hair color" => {
START_COMMAND => qr{hair colou?r:\s*}i,
VALUE_MATCH => qr{[\w\s]+},
},
"height" => {
START_COMMAND => qr{height:\s*}i,
VALUE_MATCH => qr{\d+},
},
"weight" => {
START_COMMAND => qr{weight:\s*}i,
VALUE_MATCH => qr{\d+},
},
);
foreach my $line (grep {/\w/} <DATA>) {
foreach (keys %KEY_PARSER) {
while ($line =~ /$KEY_PARSER{$_}{START_COMMAND}/) {
$line =~ s/($KEY_PARSER{$_}{START_COMMAND})\s*($KEY_PARSER
+{$_}{VALUE_MATCH})//;
next unless $2;
my ($key,$value) = ($1,$2);
chomp ($key,$value);
print "Found KEY: $key = $value\n";
}
}
}
Crap, even when munged by the magical Perl, still smells like crap.
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.