有没有更简单的方法可以将 char 添加到 perl 中数组元素的开头和结尾。
Ex:my $str ='table1,table2,table3'
my @arry = split (/,/,$str)
我喜欢输出应该看起来像
'table1','table2','table3'
所以可以在sql查询中使用
谢谢。
有没有更简单的方法可以将 char 添加到 perl 中数组元素的开头和结尾。
Ex:my $str ='table1,table2,table3'
my @arry = split (/,/,$str)
我喜欢输出应该看起来像
'table1','table2','table3'
所以可以在sql查询中使用
谢谢。
join(',', map "'$_'", @arry)
就是你要的。
但最好使用占位符:
my $str = 'table1,table2,table3';
my @arry = split(/,/, $str);
if (@arry) {
my $query = 'select * from tablename where colname in (' . join(',',('?') x @arry) . ')';
my $sth = $dbh->prepare($query);
$sth->execute(@arry);
...
}
If you are going to use DBI (https://metacpan.org/module/DBI) to work with your database, it can do it for you if you use placeholders in your queries, so that you don't have to quote values.
For example, if you want to insert something into a table:
$dbh->do("INSERT INTO table VALUES(?, ?, ?)", undef, @arry)
or die $dbh->errstr;
where @arry
is an array containing exactly 3 values to be inserted into a table.
More on this can be found here https://metacpan.org/module/DBI#Placeholders-and-Bind-Values