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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.