What is the correct way to break a line of Perl code into two?
Asked Answered
B

4

32
$ cat temp.pl
use strict;
use warnings;

print "1\n";
print "hello, world\n";

print "2\n";
print "hello,
world\n";

print "3\n";
print "hello, \
world\n";

$ perl temp.pl
1
hello, world
2
hello,
world
3
hello, 
world
$

To make my code easily readable, I want to restrict the number of columns to 80 characters. How can I break a line of code into two without any side effects?

As shown above, a simple or \ does not work.

What is the correct way to do this?

Betthezel answered 21/10, 2010 at 6:15 Comment(0)
W
51

In Perl, a carriage return will serve in any place where a regular space does. Backslashes are not used like in some languages; just add a CR.

You can break strings up over multiple lines with concatenation or list operations:

print "this is ",
    "one line when printed, ",
    "because print takes multiple ",
    "arguments and prints them all!\n";
print "however, you can also " .
    "concatenate strings together " .
    "and print them all as one string.\n";

print <<DOC;
But if you have a lot of text to print,
you can use a "here document" and create
a literal string that runs until the
delimiter that was declared with <<.
DOC
print "..and now we're back to regular code.\n";

You can read about here documents in in perldoc perlop.

Weatherbound answered 21/10, 2010 at 6:22 Comment(1)
Also note that the text returned by the heredoc contains newline characters as they are written whereas the concatenated ones do notCrinkleroot
E
15

One more thing from Perl Best Practices:

Breaking Long lines : Break long expressions before an operator. like

push @steps, $step[-1]
                  + $radial_velocity * $elapsed_time
                  + $orbital_velocity * ($phrase + $phrase_shift)
                  - $test
                  ; #like that
Eductive answered 21/10, 2010 at 6:56 Comment(1)
I hated that style before reading that book. I'd seen it on mainframe clist scripts, but Damian made a good case about how fast it is to see what's being done. And now I use it all the time. +1 for PBP!Agglutination
V
6

This is because you are inside a string. You can split the strings and concatenate using . as:

print "3\n";
print "hello, ".
"world\n";
Vareck answered 21/10, 2010 at 6:22 Comment(0)
B
2

Use ., the string concatenation operator:

$ perl
print "hello, " .
"world\n";ctrl-d
hello, world
$
Bynum answered 21/10, 2010 at 6:20 Comment(2)
print was just an example that I used. Is there a general line breaker feature for Perl?Betthezel
@Lazer: If you want a multi-line string to be single line, use .. Otherwise, perl is free-form and you can put a newline anywhere.Bynum

© 2022 - 2024 — McMap. All rights reserved.