免责声明:我第一次使用 DBI。
我有一个 MySQL 表,其中包含许多索引字段(f1、f2、f3 等),这些字段用于通过长时间运行的进程生成 WHERE 子句,这些进程迭代执行各种清理和测试操作的数据库块。
此代码的当前版本的工作方式如下:
sub get_list_of_ids() {
my ($value1, $value2, $value3...) = @_;
my $stmt = 'SELECT * FROM files WHERE 1';
my @args;
if (defined($value1)) {
$stmt .= ' AND f1 = ?';
push(@args, $value1);
}
# Repeat for all the different fields and values
my $select_sth = $dbh->prepare($stmt) or die $dbh->errstr;
$select_sth->execute(@args) or die $select_sth->errstr;
my @result;
while (my $array = $select_sth->fetch) {
push(@result, $$array[0]);
}
return \@result;
}
sub function_A() {
my ($value1, $value2, $value3...) = @_;
my $id_aref = get_list_of_ids($value1, $value2, $value3...);
foreach my $id (@$id_aref) {
# Do something with $id
# And something else with $id
}
}
sub function_B() {
my ($value1, $value2, $value3...) = @_;
my $id_aref = get_list_of_ids($value1, $value2, $value3...);
foreach my $id (@$id_aref) {
# Do something different with $id
# Maybe even delete the row
}
}
无论如何,我将在数据库中转储更多的行,并且很清楚上面的代码不会扩大规模。我可以根据其他语言想出几种方法来修复它。在 Perl 中处理它的最佳方法是什么?
需要注意的关键点是 in 的逻辑get_list_of_ids()
太长,无法在每个函数中复制;并且对所选行的操作非常多样化。
提前致谢。