You've all seen the Perl Cookbook cut2fmt function which relieves you of some of the work setting up a unpack TEMPLATE. I often need to go one further and get fields out of a record in a non-contiguous way, ie. skip bytes. This is similar to what you do in languages like SAS - and it makes life very easy when working with files. I slightly modified the cut2fmt program from the Perl Cookbook to do this. WARNING - hasn't been through exhaustive testing, and it's yours to do what you want with.
# cut2fmt part 2
sub cut2fmt2 {
my(@positions) = @_;
my $template = '';
my $lastpos = 1;
foreach $fld (@positions) {
($place,$len) = split(/-/,$fld);
if ($lastpos<=$place) {
$template .= "x" . ($place - $lastpos) . " ";
$place += $len;
}
$template .= "A" . ($len) . " ";
$lastpos = $place;
}
$template .= "A*";
return $template;
}
# Pick out fields from a fixed length file record
# by defining start pos - len eg. 8-3 = get 3 Alpha char from posn 8.
# use the string this sub returns in your unpack (or pack!) statement.
$fmt = cut2fmt2("8-3","14-6","20-3","26-2","30-1");
print "$fmt\n";
# Returns: x7 A3 x3 A6 x0 A3 x3 A2 x2 A1 A*
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.