How can I format boolean operators with perltidy?
Asked Answered
E

2

5

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?

Especial answered 27/8, 2022 at 14:45 Comment(0)
M
6

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 '&&'  ||  $op eq '||') {
        $op->{content} = " $op ";
    }
}
print $doc;

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

Mancino answered 29/8, 2022 at 22:47 Comment(0)
H
3

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.

Heartstricken answered 27/8, 2022 at 15:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.