gpt4 book ai didi

perl - 在 Perl 中,如何用空格填充字符串的一部分?

转载 作者:行者123 更新时间:2023-12-04 00:01:44 29 4
gpt4 key购买 nike

你更喜欢哪个版本?

#!/usr/bin/env perl
use warnings;
use strict;
use 5.010;

my $p = 7; # 33
my $prompt = ' : ';
my $key = 'very important text';
my $value = 'Hello, World!';

my $length = length $key . $prompt;
$p -= $length;

选项1:
$key = $key . ' ' x $p . $prompt;

选项 2:
if ( $p > 0 ) { 
$key = $key . ' ' x $p . $prompt;
}
else {
$key = $key . $prompt;
}
say "$key$value"

最佳答案

我会选择

sprintf "%-7s : %s", $key, $value;
或者
sprintf "%-*s : %s", $p, $key, $value;
而不是所有这些奇怪的东西。
来自 sprintf文档:

The flag characters

'-' The converted value is to be left adjusted on the field boundary. (The default is right justification.) The converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A '-' overrides a 0 if both are given.

The field width

An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead of a decimal digit string one may write '*' or '*m$' (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. A negative field width is taken as a '-' flag followed by a positive field width. In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

关于perl - 在 Perl 中,如何用空格填充字符串的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2486358/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com