dmorgo has asked for the wisdom of the Perl Monks concerning the following question:
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.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");
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().
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Better heredocs?
by kyle (Abbot) on Oct 30, 2007 at 20:02 UTC | |
|
Re: Better heredocs?
by doom (Deacon) on Oct 30, 2007 at 20:52 UTC | |
|
Re: Better heredocs?
by Jenda (Abbot) on Oct 31, 2007 at 14:16 UTC | |
|
Re: Better heredocs?
by dmorgo (Pilgrim) on Nov 02, 2007 at 15:57 UTC |