toolic++ ; By handling the first line separately, you can remove all the special cases that you had embedded in your regex, and thereby make it harder to mis-parse your data. The version below correctly handles whitespace in the second field.
Working, tested code: #!/usr/bin/env perl
use Modern::Perl;
my $dash_or_digits = qr{ (?: - | \d+ ) }msx;
my $string_with_spaces = qr{ \w [\s\w]*? }msx;
my $re = qr{
\A
\s* ( \d+ ) # PID
\s+ ( $string_with_spaces ) # POLS
\s+ ( \d+ ) # U(%)
\s+ ( $string_with_spaces ) # POOL_NAME
\s+ ( \d+ ) # Seq#
\s+ ( \d+ ) # Num
\s+ ( \d+ ) # LDEV#
\s+ ( $dash_or_digits ) # H(%)
\s+ ( $dash_or_digits ) # VCAP(%)
\s+ ( \w+ ) # TYPE
\s+ ( \w+ ) # PM
\s*
\z
}msx;
my $first_line = <DATA>;
chomp $first_line;
my @field_names = split ' ', $first_line;
say join ';', @field_names;
while ( <DATA> ) {
chomp;
my @fields = /$re/ or die;
warn if scalar(@field_names) != scalar(@fields);
say join ';', @fields;
}
__DATA__
PID POLS U(%) POOL_NAME Seq# Num LDEV# H(%) VCAP(%) TYPE PM
003 POLN 0 Bad name with spaces 13453 2 61443 80 - OPEN N
002 POLN 52 DemoSolutions 54068 7 61454 80 - OPEN N
Output: PID;POLS;U(%);POOL_NAME;Seq#;Num;LDEV#;H(%);VCAP(%);TYPE;PM
003;POLN;0;Bad name with spaces;13453;2;61443;80;-;OPEN;N
002;POLN;52;DemoSolutions;54068;7;61454;80;-;OPEN;N
-
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.
|