Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Fixed length file layout - cut2fmt 2

by Anonymous Monk
on Jul 22, 2002 at 06:40 UTC ( #183957=snippet: print w/ replies, xml ) Need Help??

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*


Comment on Fixed length file layout - cut2fmt 2
Download Code

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://183957]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2015-07-30 05:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (270 votes), past polls