[olug] Turn a pipe delimited file into a fixed width file

Jay Hannah jay at jays.net
Fri Apr 11 17:20:49 UTC 2003


One of my admins asked me how to do this, so I gave him 10 minutes worth
of Perl. I thought it might be of interest.

Cheers,

Jay Hannah
Omaha Perl Mongers: http://omaha.pm.org



#!/usr/bin/perl

# @lens is length of each field in the fixed width file.
my @lens = (5, 2, 28, 1, 5, 7, 8, 3, 6, 1, 1, 4, 4, 3, 2);
pipe_delimit_me("ZIP.DAT", "out.unl", @lens);
exit;

sub pipe_delimit_me {
   my ($infile, $outfile, @lens) = @_;
   open (OUT, ">$outfile") or die;
   open (IN, $infile) or die;
   while (<IN>) {
      my $line = $_;
      my $offset = 0;
      foreach (@lens) {
         my $length = $_;
         my $val = substr $line, $offset, $length;
         $val =~ s/\s+$//;
         $val =~ s/^\s+//;
         print OUT "$val|";
         $offset += $length;  # Offset for next substr call running total
      }
      print OUT "\n";
   }
   close IN;
   close OUT;
}





More information about the OLUG mailing list