PBP: 042 Heredoc Indentation

The Best Practices suggest that putting a heredoc in a deeply nested function looks funny because it has to be left-justified, and suggests creating a “theredoc” by writing a function that does nothing besides evaluate and return the heredoc.

This does solve the indentation problem, but gets more complex if you’re trying to interpolate a bunch of variables into the heredoc.  You wind up sticking them into a hashref and passing the hashref, then using those in the heredoc.  It makes for quite a complex function, and is not as simple and easy to call as the sample in the book.

It also still leaves the heredoc at the left margin.

The Perl Cookbook, in recipie 1.11, “Indenting Here Documents” suggests using a regular expression to eat all the leading spaces from the heredoc.  You get the heredoc where it has to go and can indent it properly.

I don’t usually bother with either.  Considering that the default perltidy settings will try and avoid breaking long strings by reverse-indenting them as far as needed, it is not unusual to wind up with long strings pushed back to the left margin anyway.  I just stick the heredoc in where it needs to be and am happy.

As I mentioned before, a potentially better solution is to take the literal strings out of the program and put them in data files, fit for internationalization.  But I haven’t done it and can’t tell you the pros and cons.

One Response to “PBP: 042 Heredoc Indentation”

  1. Aaron Priven says:

    And the most recent perls have <<~ to allow indented heredocs to have their indentations automatically removed.

Leave a Reply