perl - 如何保留 perl 变量的尾随空格?

标签 perl file unpack fixed-width

脚本(最初从 here 复制)将固定宽度的文本文件作为输入,重新排列列的顺序,并应输出固定宽度的文本文件。但是尾随空格被从变量中截断,这意味着输出不是固定宽度的。

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;

最佳答案

perldoc -f pack 建议:

              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.

或许您可以尝试在格式字符串中使用“a”而不是“A”?或者,您可以使用 printf 将输出字段填充到所需的宽度。

关于perl - 如何保留 perl 变量的尾随空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12167991/

相关文章:

perl - 在 macOS Mojave 下安装 DBD::mysql 时遇到问题

xml - 无法定位对象方法 setData - 将值保存在 XML 文件中

c++ - 在 C++ Visual Studio 2010 中创建输出文件

Lua解包bug?

matlab - Octave 的矢量解包

windows - 如何更新 Perl 命令行应用程序上的进度显示?

Perl 命令行搜索并替换为多个表达式

c# - (手动)序列化和反序列化二叉搜索树

c++ - 如何读取目录中最后修改的文件的文件名?

perl - 将十六进制字符串转换为二进制