in reply to Why SprintF?

My favorite way to generate SQL statements is with sprintf. So instead of using just concatenation:
## silly example without DBI quoting my $sql = "insert into mytable (" . join(",", @columns) . ") values (" . join(",", @values) . ")";
.. (which I happen to think is very ugly) I can use sprintf:
my $sql = sprintf "insert into mytable (%s) values (%s)", join(",", @columns), join(",", @values);
So in this case, I really like the mini string-templating possiblities of s/printf, but of course I don't want to print the SQL statement to the screen, I want to send it to the database. Hence, sprintf.

This is nothing special about SQL statements, only that I often want to include the result of nontrivial expressions (i.e, not just $string) in the string. I can't interpolate a join statement (easily) inside a double-quoted string, and stringing together concatenation operations is ugly, so I use sprintf, which is easier to read (for me at least).

blokhead

Replies are listed 'Best First'.
Re^2: Why SprintF?
by davidrw (Prior) on Jan 30, 2006 at 16:16 UTC
    If you are feeding those SQL statements to DBI/|DBD::*, placeholders instead of the join on @values can save a lot of problems..
    my $sql = sprintf "insert into mytable (%s) values (%s)", join(",", @columns), join(",", map {'?'} @values); # couple different ways to + do this part $dbh->do($sql, {}, @values);
    Or for this example, SQL::Abstract can be very useful as well:
    use SQL::Abstract; my $sql = SQL::Abstract->new; my %data; @data{@columns} = @values; #hash slice to get column=>value pairs my($sql, @bind) = $sql->insert($table, \%data); $dbh->do($sql, {}, @bind);