1

Suppose I have some Perl code that looks like this

      use Data::Dump q[pp];
  sub something{
      return 2 + 2;
  }

I want it to be formatted by perltidy as

use Data::Dump q[pp];
sub something{
    return 2 + 2;
}   

That is, all leading whitespace eliminated and all lines aligned left, but then with indent rules applied. I've tried -dws but that didn't work and no-one of the other options seems to do anything. Is this possible?

sail0r
  • 445
  • 1
  • 5
  • 18
  • Can always strip the leading whitespace as a separate step... `perl -pe 's/^\s+//' foo.pl | perltidy > foo_pretty.pl` – Shawn Oct 11 '21 at 23:12
  • But that's the perltidy output I get (Except with a blank line between the `use` and the subroutine)... – Shawn Oct 11 '21 at 23:20
  • @Shawn and your input has leading spaces in front of all lines? If so, what `perltidy` settings are you using? – sail0r Oct 11 '21 at 23:29
  • Same here, if _all_ lines have some indent then `perltidy` doesn't touch that. But it does its thing, other than that; I take it that it has no grounds for touching overall indentation. I skipped over its man page and found no options for that. However, if any one line has 0 indent (like shebang line) then it does adjust overall indentation. So ... perhaps just add one (1) line? Like a comment, timestamp, anything. – zdim Oct 12 '21 at 00:06
  • No, no leading spaces except for the indented body of the sub. No options at all, or just `-dws`. (The template perl file I copy & pasted into does have a shebang, though.) – Shawn Oct 12 '21 at 00:38
  • Ok, if there is a shebang line in the typical way, with zero left space, the rest of the code below can be about as bizarrely indented as you please and perltidy does the right thing. Remove that shebang line and the desired behavior does away completely. There is nothing so special with shebang lines either. As long as the first non-empty line is indented 3 or fewer spaces the rest of the code indents properly. I can't see any documentation on this so I am not sure if it's a bug or feature. – sail0r Oct 12 '21 at 02:56
  • I should say instead of "first non-empty" the "first line with something other than whitespace". For example if the first line is " 2;" (one space followed by a numeric literal and then a semi-colon) the indenting is correct. – sail0r Oct 12 '21 at 03:00

1 Answers1

1

As shown it is not possible.

Some additional experimentation shows that as long as there is at least one line (which can contain pretty much anything) that is indented fewer than four spaces at the beginning of the file perltidy will indent as hoped for in the original question.

The solution for this specific sort of example is to include pre-processing steps in a Makefile which simply eliminates all blank lines and left space before running perltidy. This solves the problem.

sed -i -e 's/^[ \t]*//' file.pl
sed -i -e '/./!d' file.pl
perltidy file.pl
sail0r
  • 445
  • 1
  • 5
  • 18