I usually use simple quotes, but sometime I get very long lines which I can't break and also need to use escape characters, so I get something like this:
my $str = "select query_accession,query_tag,hit_accession,hit_tag,significance from summaryTables where query_id = \'$query_id\';"
I know there are various other ways for representing strings in Perl. What would you recommend?
UPDATE Thank you all guys for the SQL-related suggestions. I learn some valuable stuff, but, my question remains (as a general one, regardless of SQL): is there some operator that allows quoting without catching line breaks?
what I do now is something like:
my $str = "123 123 456 sdndfnd sdfdmd " .
"dfsdjkfs 343489 dfjsdj 3 34kdfsk kd " .
"fd kd9534 rfg 546 5";
which is quite ugly.
$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.
If you put a back-slash \ in a double-quoted string, Perl will think you want to escape the next character and do its magic.
Another way to represent a double-quoted string is to use the qq operator and then choose your own string delimiters.
Normally the $$ is used to print the current process ID. print $$;
I like here documents, although some people despise them because the terminator has to appear at the beginning of the line despite your indent level.
my $str = <<"SQL";
SELECT
query_accession,
query_tag,
hit_accession,
hit_tag,
significance
FROM
summaryTables
WHERE
query_id = ?
SQL
Perl v5.26 introduced indented here docs, like Ruby has. This looks almost the same, and if StackOverflow hasn't messed with the formatting, you should see that the final SQL
marker is not flush left like the previous example:
my $str = <<~'SQL';
SELECT
query_accession,
query_tag,
hit_accession,
hit_tag,
significance
FROM
summaryTables
WHERE
query_id = ?
SQL
I also like formatting my SQL so I can easily see the structure in the statement, but that's a personal style. You might like something different.
No. All of Perl 5's string creation methods know about and include newlines. You can either use the concatenation operator as you did in your question, or abstract away the code needed to fix the problem:
#!/usr/bin/perl
use strict;
use warnings;
sub single_line {
my @strings = @_;
for (@strings) {
s/\s+/ /g;
s/^\s+|\s+$//g;
}
return wantarray ? @strings : $strings[0];
}
my $sql = single_line "
select query_accession,query_tag,hit_accession,hit_tag,significance
from summaryTables
where query_id = ?;
";
print "[$sql]\n";
Look in perlop's Quote-Like Operators. Use qq
for double quotes and q
for single quotes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With