corfuitl has asked for the wisdom of the Perl Monks concerning the following question:


I have two sentences that share the same symbols (i.e. /*-) and would like to fix the whitespaces of the second sentence according the whitespaces of the first. For instance:

This is a perl script/program.

C'est un perl script / programme.

The second senctence should be:

c'est un perl script/programme.

Please note that the sentence can contain lots of symbols. In that case, ideally the first should align with the first, the second with the second and so on.

Can you please help me?

Thanks in advance.

Replies are listed 'Best First'.
Re: Fix whitespace around symbols
by Corion (Pope) on Mar 19, 2015 at 08:42 UTC

    What code have you already written?

    Personally, I would extract the "special" symbols and their surrounding whitespace from the first sentence and then replace the elements accordingly in the second sentence:

    my %symbols = ( '/' => [], '*' => [], '-' => [], ); $_= "This is a perl script/program."; push @{ $symbols{ '/' }}, m!(\s*[/]\s*)!; push @{ $symbols{ '*' }}, m!(\s*[*]\s*)!; push @{ $symbols{ '-' }}, m!(\s*[-]\s*)!; my $target= "C'est un perl script / programme"; $target =~ s!\s*([/*-])\s*!shift $symbols{ $1 }!ge;


      Thanks for your reply. I haven't written any code because I don't know how to start. I would like to do it in perl but other script languages are welcome.

      I have tried your code and it works when the sentence contains one symbol. In case of more symbols, they are omitted from the second sentence.


        I can't replicate the problem. When I run the program with the two sentences:

        $_= "This is a perl script/program- code."; my $target= "C'est un perl script / programme - codele";

        I get as the result in $target:

        C'est un perl script/programme- codele

        ... which is what I expect. If you tell us the exact input data and the exact output data you get, maybe we can work on finding the cause.

Re: Fix whitespace around symbols
by Anonymous Monk on Mar 19, 2015 at 08:38 UTC