perl - 如何在 Perl 中垂直对齐文本行?

标签 perl text-alignment

假设两行文字除标点符号外,逐字对应。如何使它们垂直对齐?

例如:

$line1 = "I am English in fact";
$line2 = "Je suis anglais , en fait";

I want the output to be like this:

I   am     English       in   fact
Je  suis   anglais   ,   en   fait  .

I've come up with the following code, based on what I've learnt from the answers to my previous questions posted on SO and the "Formatted Output with printf" section of Learning Perl.

use strict;
use warnings;

my $line1 = "I am English in fact";
my $line2 = "Je suis anglais , en fait.";

my @array1 = split " ", $line1;
my @array2= split " ", $line2;

printf "%-9s" x @array1, @array1;
print "\n";
printf "%-9s" x @array2, @array2;
print "\n";

不满意。输出是这样的:

I        am       English  in       fact
Je       suis     anglais  ,        en       fait.

Can someone kindly give me some hints and suggestions to solve this problem?

Thanks :)

Updated

@ysth sent me on the right track! Thanks again:) Since I know what my own date looks like,for this sample, all I have to do is add the following line of code:

for ( my $i = 0; $i < @Array1 && $i < @Array2; ++$i ) {
    if ( $Array2[$i] =~ /,/ ) {
        splice( @Array1, $i, 0, '');
    }
}

Learning Perl 简单提到,splice 函数可以用来删除或添加数组中间的项。现在谢谢,我又扩充了我的 Perl 知识库:)

最佳答案

从您的样本输出来看,您似乎想做的是添加额外的 一个数组中只有标点符号而另一个数组中没有的空字符串元素。 这非常简单:

for ( my $i = 0; $i < @array1 && $i < @array2; ++$i ) {
    if ( $array1[$i] =~ /\w/ != $array2[$i] =~ /\w/ ) {
        if ( $array1[$i] =~ /\w/ ) {
            splice( @array1, $i, 0, '' );
        }
        else {
            splice( @array2, $i, 0, '' );
        }
    }
}

或者,更奇特的是,使用标志位 en passant:

given ( $array1[$i] =~ /\w/ + 2 * $array2[$i] =~ /\w/ ) {
    when (1) { splice( @array1, $i, 0, '' ) }
    when (2) { splice( @array2, $i, 0, '' ) }
}

关于perl - 如何在 Perl 中垂直对齐文本行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1736835/

相关文章:

Perl:安全评估?

perl - 为什么我的 Perl 系统调用失败并出现点?

perl - perl 反引号中使用的 tail 命令

java - 在 Perl 中处理 Java stdout 和 stderr

bash - 右文本对齐 - bash

ios - 在 iOS 上使用 NSMutableAttributedString 对同一标签进行多文本对齐

html - 将文本基线与图像的特定垂直比对齐

Python 正则表达式全局用空格替换尾随零

html - Bootstrap 3 如何在表头中间制作 "aaaaa"?

perl - 如何判断使用的模块是否是纯 perl?