gpt4 book ai didi

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

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

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

例如:

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

I want the output to be like this:

I   am     English       in   factJe  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       factJe       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/

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