Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

janus (3624)

janus
  (email not shown publicly)
http://janus.errornet.de/

Journal of janus (3624)

Wednesday January 27, 2010
07:09 AM

Hint: Formatting SQL in Perl code

[ #40134 ]

Usually i'm telling people NOT to put their SQL into the code, pretty
much the same as with templates.

As that needs code to get the SQL from the outside it isn't always
what you want. And with SQL there's more than just ``put different
languages into different files'', it's also about formating.

To achieve that i was using heredocs for a while with different
delimiters until i realized that a semicolon is the best option i
can think of:

$sql = <<';';
SELECT
        *
FROM foo
WHERE
      id = $1
;
... which is also pretty nice for copy&waste and has no quoting issues either.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • I've never been a big fan of heredocs - mainly because they break indentation. When I put SQL in code, I tend to use the single quote operator with curly braces for delimiters:

    $sql = q{
        SELECT
                *
        FROM foo
        WHERE
              id = $1
    };

    • $sql = q;
          SELECT
                  *
          FROM foo
          WHERE
                id = $1
          ;