Home > Software engineering >  How can I format boolean operators with perltidy?
How can I format boolean operators with perltidy?

Time:08-30

To my knowledge, perltidy is extremely handy and helpful when it comes to code formatting. However, I haven't found a way to fine-tune perltidy. For example, I need the && and || formatted so that there are two spaces before and after them. Like this:

$some && $x > 7;

Can I do it? If so, how?

CodePudding user response:

perltidy does not have an option to add two spaces before and after operators.

Furthermore, if you manually add 2 spaces, then run perltidy, it will convert the 2 spaces to a single space by default. However, there are options for skipping selected lines of code.

CodePudding user response:

It's easy enough to rig up your own tidy script with PPI that you can run after perltidy. Proof-of-concept:

use PPI;
my $doc = PPI::Document->new($ARGV[0]);
for my $op (@{$doc->find('PPI::Token::Operator')}) {
    if ($op eq '&&' || $op eq '||') {
        $op->{content} = " $op ";
    }
}
print $doc;

And if we run this script on itself, we get:

$ perl je8tidy.pl je8tidy.pl
use PPI;
my $doc = PPI::Document->new($ARGV[0]);
for my $op (@{$doc->find('PPI::Token::Operator')}) {
    if ($op eq '&&'  ||  $ops eq '||') {
        $op->{content} = " $op ";
    }
}
print $doc;

it did insert the extra spaces around the only '||' operator on line 4.

  • Related