%data = ('col_1'=>'foo',
'col_2'=>'bar',
'col_3'=>'baz');
####
insert_hash("table", \%hash);
####
sub insert_hash {
my $table_name = shift;
my $rowref = shift;
my %row = %$rowref;
# ?c? and ?v? are placeholders
# Any better ideas for placeholders to pretty up the regexes?
my $sql = "insert into $table_name (?c?) values (?v?)";
foreach (keys %hash) {
$sql =~ s/\?c\?/$_,\?c\?/g;
$sql =~ s/\?v\?/$hash{$_},\?v\?/g;
}
# Pull off the last comma (extraneous) and the placeholders
$sql =~ s/,\?c\?//g;
$sql =~ s/,\?v\?//g;
return $sql;
}