Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a line-break to a Perl script print

Tags:

macos

perl

I'm having an issue with a basic perl script. Below is the script.

$message = "Hello, World!";
print $message;

The problem is that it prints then on the same line has my username command prompt. I have provided a screenshot of the described problem. I just want to add a line break to the script. Is this possible?

enter image description here

like image 503
fsimkovic Avatar asked Dec 19 '22 23:12

fsimkovic


1 Answers

I just want to add a line break to the script. Is this possible?

Yep -- use the newline character, \n.

my $msg = "Hello World!\n";

Beware the difference between single and double quotes in perl. The above will print with a newline. But this:

my $msg = 'Hello World!\n';

Will print a literal \n at the end. The difference is that double quoted strings are interpolated: variables and escape sequences such as \n are substituted predictably. Single quoted strings aren't, so:

print '$msg';

Will also print literally, $msg, and not the contents of the variable $msg.

\n is more or less universal; I don't know if it originates with C or something before that, but it and various other backslash characters (e.g., \t for tab) are common to all the languages I know of, including the shell. The correct term is actually escape sequence as \ is an escape character affecting the interpretation of the next character. In order to print a single backslash in an interpolated string, you must use the escape first:

print "\\ <- A single backslash\n";

The backslash is also used as an escape character in regular expressions. The difference between single and double quoted strings is not as universal as the backslash escape, but it is used in some other high level languages.

like image 187
CodeClown42 Avatar answered Dec 22 '22 14:12

CodeClown42