Characters \n (backslash and n) to Perl

Quite often in program code in Perl can meet a combination of symbols \n.

In the Perl programming language and many other languages programming these two symbols mean next to a single character, the newline. Further details.

Here is a sample code which uses \n:

▶ Run
#!/usr/bin/perl

print "line 1\n";
print "line 2\n";

If you save this text to a file script.pl and run it through perl script.pl, it will appear on the screen:

line 1
line 2

The program output shows that the text line 1 is on one line and the text line 2 on the other. It happened due to the symbols \n in the team print "line 1\n";. Keyword printdisplays on the screen of their arguments. Here, the argument is the string "line 1\n". Perl displays all characters from the string. The combination of symbols \n is one special symbol that indicates that the text following this symbols should be output on a new line.

The use of translated strings

You can write a program which works exactly the same as the previous program without the use of symbols \n in the code. Here's how to do it:

▶ Run
#!/usr/bin/perl

print "line 1
";
print "line 2
";

Here is the symbol \n used a real newline in your code.

The use of the symbol \n and this line creates absolutely the same string. Here is an example of code that shows that this is true (when you start this program displays strings are the same):

▶ Run
#!/usr/bin/perl

my $str1 = "line\n";

my $str2 = "line
";

if ($str1 eq $str2) {
    print "strings are the same";
} else {
    print "strings differ";
}

Single and double quotation marks

Characters \n are transformed into the line only when used in double quotes. If you use symbols \n, in single quotes, then they will remain two characters — backslash and the Latin letter n.

▶ Run
#!/usr/bin/perl

print 'line 1\n';
print 'line 2\n';

When running this code the screen will display the text

line 1\nline 2\n

\n is a single character

You can be sure that when you use \n in double quotes is actually a single character.

▶ Run
#!/usr/bin/perl

print length("\n"), "\n";
print length('\n'), "\n";

This program displays the number 1 first line and 2 on the second line. \n in double quotes is one character, \n in single quotes is two characters.

say

Very often the characters \n are used together c print to beautiful to reflect something in the console. Instead, you can use the keyword say. say works exactly the same as print — displays on the screen its arguments, but also displays the symbol \n line.

So our program could be written like this:

▶ Run
#!/usr/bin/perl

use feature qw(say);

say "line 1";
say "line 2";

In order to work print nothing further to be done, but in order to work say code Perl program, you need to add a line use feature qw(say);. Without it will not work.

Other articles

Comments