3

Script (originally copied from here) takes a fixed-width text file as input, rearranges the order of columns, and should output a fixed-width text file. But trailing spaces are being truncated from the variables, which means the output isn't fixed-width.

open(INPUT, "</home/ecom/tmp/citiBIG/GROUP.txt");
open(OUTPUT, ">/home/ecom/tmp/citiBIG/GROUP2.txt");

my $LINEFORMAT = "A2 A7 A14 A4 A2 A2 A4 A12 A25 A30 A26 A40 A40 A40 A25 A4 A12 A14 A2 A8 A12 A70 A8"; # Adjust to your
 field widths

while(<INPUT>) {
    chomp;
    my($Null0, $EmpNum, $CcNumber, $Null1, $CcExpYy, $CcExpMm, $Null2, $Title, $LastName, $FirstName, $HolderName, $Ad
dress1, $Address2, $Address3, $Suburb, $State, $PostCode, $Null3, $AreaCode, $WorkPhone, $Null4, $Email, $GroupName) =
 unpack($LINEFORMAT, $_);

    print OUTPUT $EmpNum . "               " . "~" . $LastName . "~" . $FirstName . "~" . $Title . "        " . "~" .
$Address1 . "~" . $Address2 . "~" . $Address3 . "~" . $Suburb . "~" . $PostCode . "~" . $State . "~" . $AreaCode . "~"
 . $WorkPhone . "~" . $CcNumber . "~" . $CcExpMm . "~" . $CcExpYy . "~" . $HolderName . "~" . $Email . "~" . $GroupNam
e . "                      " . "~" . "\n";
}


close INPUT;
close OUTPUT;
zostay
  • 3,985
  • 21
  • 30
Stew-au
  • 434
  • 5
  • 13

1 Answers1

5

perldoc -f pack suggests:

              o   The "a", "A", and "Z" types gobble just one value, but pack
               it as a string of length count, padding with nulls or
               spaces as needed.  When unpacking, "A" strips trailing
               whitespace and nulls, "Z" strips everything after the first
               null, and "a" returns data without any sort of trimming.

Maybe you could try "a" instead of "A" in the format string? Alternatively you could use printf to pad the output fields to the desired widths.

sti
  • 11,047
  • 1
  • 27
  • 27
  • You could also add a second `$LINEFORMAT` with the fields rearranged as needed for output and then use `pack` to send the data back out in a fixed width. – zostay Aug 28 '12 at 22:15
  • Marking as correct answer... using "a" instead of "A" worked perfectly. Thanks @sti for your rapid and valuable contribution. – Stew-au Aug 28 '12 at 23:54