Here's a slightly improved heredoc idiom. Not my invention, but I forget where I got it. Probably from here on perlmonks. Shown here in the context of a subroutine, but it doesn't have to be in that context:
sub get_content { my $name = shift; my $content; ($content = <<" END") =~ s/^\s{1,4}//gm; <p>$name</p> <ul> <li>foo</li> <li>bar</li> </ul> END return $content; } print get_content("stuff");
I like this heredoc idiom because it keeps things neat, both with the nice indenting in the Perl code, and also, when it's generating HTML/XML/FooML, it lets me keep the generated text neat as well, since it doesn't remove all leading whitespace, just the perl-code-level indentation.

But what I don't like is that it makes the code brittle in the face of possible changes to the indentation at the beginning. The regular expression part is not the problem. The problem is the match on "    END", which is set in this example to start with four literal spaces.

If someone comes along with an editor that converts four spaces into tabs, the code silently breaks. Not good. Or if someone changes the indentation to two spaces instead of four, it breaks as well.

Is there any better way to specify the "    END" so it will match in a more robust way?

By the way, I do realize that there are other ways to generate HTML (CGI, templates, etc.) but my question is not about how to generate HTML. The HTML shown is just a contrived example. The question is really about better ways to do heredocs.

Update: see the new technique below achieving the same ends (and even better, thanks to Jenda's idea to make the indent size generic) using qq().


In reply to Better heredocs? by dmorgo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.