package PM::FixedWidthFile;
use strict;
use warnings;
use autodie;
use Exporter qw{import};
our @EXPORT_OK = qw{populate_file};
use Carp;
sub populate_file {
my ($fh, $record_length, $field_data) = @_;
for my $fields (@$field_data) {
my $line = pack 'A' . $record_length;
my $offset = 0;
_add_field(\$line, \$offset, @$_) for @$fields;
print {$fh} $line, "\n";
}
return;
}
sub _add_field {
my ($line_ref, $offset_ref, $length, $data, $r_align) = @_;
if ($length < length $data) {
croak "Data [$data] too large for field of length [$length]";
}
my @dat_pad = ($data, ' ' x ($length - length $data));
substr($$line_ref, $$offset_ref, $length)
= join '' => @dat_pad[$r_align ? (1, 0) : (0, 1)];
$$offset_ref += $length;
return;
}
1;
=head1 NAME
PM::FixedWidthFile - TODO (for Jake): module documentation in POD format
####
use PM::FixedWidthFile qw{populate_file};
...
my $record_length = ...;
my $outfile = ...;
my $file_data = ...;
open my $fh, '>', $outfile;
populate_file($fh, $record_length, $file_data);
####
#!/usr/bin/env perl
use strict;
use warnings;
use autodie;
use PM::FixedWidthFile qw{populate_file};
my $fixed_width_file_base = './pm_fixed_width_file.out_';
my $record_length = 32; # not including line terminator
my @multi_file_data = (
[
[ [10, ''], [10, 123], [10, 456] ],
],
[
[ [10, ''], [10, 123], [10, 456] ],
[ [10, ''], [10, 123, 1], [10, 456] ],
[ [10, ''], [10, 123], [10, 456], [2, 78] ],
],
[
[ [10, ''], [10, 123], [10, 456], [2, 78] ],
[ [10, ''], [10, 123], [10, 456], [2, 789] ],
],
);
for my $i (0 .. $#multi_file_data) {
my $outfile = $fixed_width_file_base . $i;
print "Populating: $outfile\n";
open my $fh, '>', $outfile;
populate_file($fh, $record_length, $multi_file_data[$i]);
close $fh;
system qw{cat -vet}, $outfile;
unlink $outfile; # my housekeeping
}
####
Populating: ./pm_fixed_width_file.out_0
123 456 $
Populating: ./pm_fixed_width_file.out_1
123 456 $
123456 $
123 456 78$
Populating: ./pm_fixed_width_file.out_2
Data [789] too large for field of length [2] at ./pm_fixed_width_file.pl line 32.