I got bored and gave this as an answer to
a question today, but I figured it might have broader uses. (Not to me, of course, since I don't deal with data like this, but maybe for some of you.) It will figure out column headings and extract fixed-width ASCII fields based on them. It assumes each heading is a single word (uses the spaces between headings to determine field length), but can be adapted with a regex in the code comments to work around that.
use Data::Dumper;
my (@keys, $format, @data, @sizes);
$_ = <DATA>;
# assumes spaces between fields.. a more robust regex,
# allowing multiple words in fields but requiring at
# least 2 spaces between fields could be:
# /\G(\S+(?:\s\S+)*)\s+/g
while (/\G(\S+)\s+/g) {
push(@keys, $1);
push(@sizes, $+[0]-$-[0]);
}
$format = join("", map { "A$_" } @sizes);
while (<DATA>) {
# if you want a hashref for each line:
my $i;
push(@data, { map { ($keys[$i++], $_) } unpack($format, $_) } );
# else, take out references to @keys above and just use this:
# push(@data, [ unpack($format, $_) ] );
}
print Dumper(\@data);
__DATA__
Name ID PS Gender Age Month Code
+ Cap Pool
LName, FName 99999 99 M 99.9 12/2000 Add
+ 99.99 99.99
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.