How to vertically align lines of text in Perl?

Suppose that two lines of text match each other by word, with the exception of punctuation marks. How to make them vertical align?

For example:

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

I want the result to be like this:

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

I came up with the following code based on what I learned from the answers to my previous questions posted in SO and the section "Formatted output with printf" in 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";

This is not satisfying. Output:

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

Can someone kindly give me some tips and suggestions for solving this problem?

Thanks:)

@ysth ! :) , , :

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

Learning Perl , . , Perl:)

+3
1

, , , , , . :

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

Source: https://habr.com/ru/post/1722905/


All Articles