To begin with your concrete example ...
The specification looks something like -- fieldA is from character 9 to 14
my $TEMPLATE = '@8A6'; # oops, originally posted without the quotes
while (<DATA>) {
my @fields = unpack $TEMPLATE, $_;
# for output try pack or printf
}
This generalizes. The template for unpack should be machine-generated, to avoid off-by-one errors and other typos.
In what follows, let's suppose you have collected a list of column specifications. Each specification tells you
- a field name,
- an offset, and
- the width of the field in your fixed-width extract.
You might get this from a config file of some sort, or as the result set from a database query, if you happen to have saved your parse specifications in a database table.
use DBI;
my $dbh = ...
my $sth = $dbh->prepare(
'SELECT field, offset, width'
. ' FROM Source_Field'
. ' WHERE source = ?;'
);
my $source = 'input_file.txt';
$sth->execute($source);
my $template;
my @fields;
while (my $column_spec = $sth->fetchrow_hashref() ) {
my ($field, $offset, $width)
= @$column_spec{qw(field offset width)};
$template .= "\@${offset}A$width";
push @fields, $field;
}
open my $reader, '<', $source;
while (<$reader>) {
my %value_of;
my @values = unpack($template, $_);
@value_of{@fields} = @values;
# you've got your current record in a hash
# print it or save it somewhere
}
-
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.