Using a hash to store the variables could actually make the construction of the SQL statements easier and clearer. If you happen to be building an "insert into my_table ..." sort of statement, a hash makes this very simple to do via a "for" loop -- e.g.:
and of course, there are shorter ways to do the same thing:... my $col_spec = my $val_spec = "("; for my $column ( keys %data ) { $col_spec .= "$column,"; $val_spec .= "$data{$column},"; } $col_spec =~ s/,$/\)/; $val_spec =~ s/,$/\)/; my $sql = "insert into my_table $col_spec values $val_spec";
Similar methods apply for update and select statements, using a loop to assemble the "col=val" pairs and "where" clause conditions.my $col_spec = join( ",", sort keys %data ); my $val_spec = join( ",", map { $data{$_} } sort keys %data ); my $sql = "insert into my_table ($col_spec) values ($val_spec)";
If the basic form of the sql statement will always involve the same set of columns and conditions, you should be using the DBI "prepare()" method with parameterized values (using the "?" placeholder, and passing the values as a list to the "execute()" method).
Also, remember that you can use any sort of whitespace as part of an SQL statement, including line-feeds and tabs, so even long constructs can be formatted so that they are not difficult to read.
update: as pointed out in the next reply below, the values being assembled should be quoted if you are not using the parameterized form of sql statement. (Thanks, and ++, blokhead!)
In reply to Re: Creating variables while using 'strict'
by graff
in thread Creating variables while using 'strict'
by nedals
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |