Perl Printf 指定长度的两个字符串

sfr*_*sfr 0 perl printf

我正在打印一个需要格式化的字符串。我想使用存储在另一个变量中的一组字符来打印 printf,但我不确定如何执行此操作。

my $max_len = max map length, keys %hash;
printf ("%s %s\n", $string1, ":$string2");

Run Code Online (Sandbox Code Playgroud)

显然这是输出,string1 :string2但我想要的是第一列的总宽度为 $max_len。我怎样才能做到这一点?

ike*_*ami 5

%-4s 将通过附加空格来填充值,直到它占用四个字符。

my $max_len = max map length, keys %hash;

for my $key (keys(%hash)) {
    printf("%-{$max_len}s %s\n", $key, $hash{$key})
}
Run Code Online (Sandbox Code Playgroud)

您可以使用*to tellprintf使用参数作为字段宽度。

my $max_len = max map length, keys %hash;

for my $key (keys(%hash)) {
    printf("%*s %s\n", -$max_len, $key, $hash{$key})
}
Run Code Online (Sandbox Code Playgroud)

或者

my $max_len = max map length, keys %hash;

for my $key (keys(%hash)) {
    printf("%-*s %s\n", $max_len, $key, $hash{$key})
}
Run Code Online (Sandbox Code Playgroud)