简体   繁体   中英

How do I do vertical alignment of lines of text in Perl?

Suppose two lines of text correspond to each other word by word except for the punctuation marks. How do I make vertical alignment of them?

For example:

$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";

It is not satisfying. The output is this:

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 briefly mentions that splice function can be used to remove or add items in the middle of array. Now thanks, I've enlarged my Perl knowledge stock again :)

From your sample output, it seems what you are trying to do is to add extra empty string elements where there is just punctuation in one array but not in the other. This is fairly straightforward to do:

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, '' );
        }
    }
}

Or, somewhat more fancy, using flag bits en passant:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM