sub add_foo { my @expected_fields = qw/bar blah/; my ( @insert_flds, @insert_vals ); for my $f ( @expected_fields ) { my $v = shift; next unless ( defined( $v ) and length( $v )); push @insert_flds, $f; push @insert_vals, $v; } my $sth = $dbh->prepare_cached( 'insert into foo (' . join( ',', @insert_flds ) . ') values (' . join( ',', ('?') x @insert_flds ) . ')' ); $sth->execute( @insert_vals ); return $dbh->last_insert_id( undef, undef, 'foo_id' )); }