在 Perl 中,如何用空格填充字符串的一部分? [英] How can I pad part of a string with spaces, in Perl?

查看:47
本文介绍了在 Perl 中,如何用空格填充字符串的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你更喜欢哪个版本?

#!/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"

推荐答案

我不喜欢选项 2,因为它引入了一个不必要的特殊情况.

I don't like option 2 as it introduces an unnecessary special case.

我会重构提示后缀的构造:

I would refactor out the construction of the prompt suffix:

    # Possible at top of program
    my $suffix =  ( ' ' x $p ) . $prompt;

    # Later...

    $key .= $suffix ;

这篇关于在 Perl 中,如何用空格填充字符串的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆