Description: |
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*
|