Search code examples
perlstringquotes

How can I quote a long string in Perl?


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.


Solution

  • 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";