Sourcecode
Sourcecode

Reputation: 315

Add char to the array elements

Is there any easier way to add char to the beginning and end of array elements in perl.

Ex:my $str ='table1,table2,table3'

my @arry = split (/,/,$str)

I like the output should look like

'table1','table2','table3'

So it can be used in sql query

Thanks.

Upvotes: 1

Views: 1741

Answers (2)

Nikolay A
Nikolay A

Reputation: 51

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

Upvotes: 3

ysth
ysth

Reputation: 98398

join(',', map "'$_'", @arry)

is what you are asking for.

But it's much better to use placeholders:

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);
    ...
}

Upvotes: 9

Related Questions