in reply to Re^4: How to add quotes to comma separated values in a String (updated)
in thread How to add quotes to comma separated values in a String
You're making a lot of assumptions about the data, whereas I assumed that "CAT,DOG,BIRD,COW" was just an example and not the actual input data, so we really don't know what it'll be ("be liberal in what you accept"). Knowing how to do it in plain Perl is of course useful, but personally I'd prefer the first solution people come across to be a robust one - hence the somewhat dogmatic statement, but hopefully for a good reason ;-) I also agree entirely with Your Mother's posts.
If all your assumptions hold, then sure, it's fine to use plain Perl, but even then I would have written something like the following - just one more line of code to protect against the input changing unexpectedly:
my $input = "CAT,DOG,BIRD,COW"; $input =~ /\A\w*(?:,\w*)*\z/ or die "invalid input format"; my $str = join ',', map { "'$_'" } split /,/, $input;
I did assume that the OP, since they are doing work with a database, will have a $dbh lying around. Note that our two pieces of code really aren't that different - only a couple more characters for extra protection :-) Also note that using the database driver for quoting should take care of possible quoting differences between databases.
my $str = join ',', map { $dbh->quote($_,'VARCHAR') } @values; my $str = join ',', map { "'$_'" } @values;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: How to add quotes to comma separated values in a String (updated)
by Laurent_R (Canon) on Feb 13, 2018 at 23:16 UTC | |
by haukex (Archbishop) on Feb 16, 2018 at 14:01 UTC |