Perl格式化字符串

时间:2016-06-03 11:00:40

标签: perl format string-formatting

我试图格式化一个包含3个列的字符串,第一列数据长度可能不同,所以我不知道如何以正确的方式格式化我的字符串。

for my $k(keys %results) {
   my ($k1,$k2);
   # $k1 and $k2 are always equal to '-' or '+'
   # $k = "nnn_12_555_addd";
   ...
   format STDOUT =
@<<<<<<<<<< @> @>
$k, $k1, $k2
.
   write;
}

如何让第一列@<<<<保持正确的尺寸?如果$k值超过指定的<,则会从输出中的该值中丢失一部分...

示例输入

$k1 = '+'
$k2 = '-'

$k = 'aaa_bbb'
output:
aaa_bbb            +    -

$k = 'aaa_bbb_ccc'
output:
aaa_bbb_ccc        +    -

$k = 'aaa_bbb_ccc_ddd'
output:
aaa_bbb_ccc_ddd    +    -

1 个答案:

答案 0 :(得分:3)

我建议您忘记Perl format并使用printf代替

use strict;
use warnings 'all';

my $k1 = '+';
my $k2 = '-';

for my $k (qw/ aaa_bbb  aaa_bbb_ccc  aaa_bbb_ccc_ddd /) {
    printf "%-20s%-5s%-5s\n", $k, $k1, $k2;
}

输出

aaa_bbb             +    -    
aaa_bbb_ccc         +    -    
aaa_bbb_ccc_ddd     +    -    


更新

如果要将第一列宽度调整为最长值,可以在printf中使用动态字段宽度。像%*s这样的格式说明符从参数列表中获取两个值:字段的整数宽度和字符串

程序看起来像这样

use strict;
use warnings 'all';

use List::Util 'max';

my $k1 = '+';
my $k2 = '-';

my @k_vals = qw/ aaa_bbb  aaa_bbb_ccc  aaa_bbb_ccc_ddd  aaa_bbb_ccc_ddd_eee /;
my $w = max map length, @k_vals;

for my $k ( @k_vals ) {
    printf "%-*s %-5s%-5s\n", $w, $k, $k1, $k2;
}

输出

aaa_bbb             +    -    
aaa_bbb_ccc         +    -    
aaa_bbb_ccc_ddd     +    -    
aaa_bbb_ccc_ddd_eee +    -