Search code examples
perlperl-tidy

How can I format boolean operators with perltidy?


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?


Solution

  • 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.