Bootstrap FreeKB - Perl (Scripting) - new lines \n and carriage returns \r
Perl (Scripting) - new lines \n and carriage returns \r

Updated:   |  Perl (Scripting) articles

Let's say you have the following Perl script.

#!/usr/bin/perl
use strict;
use warnings;

my $greeting = "Hello World\n\n";
print "greeting = $greeting";

 

Running this script should return the following, where there is an empty line.

[john.doe@localhost ]$ perl ~/testing.pl
greeting = Hello World

[john.doe@localhost ]$

 

Almost always, chomp is used to remove trailing new lines from a variable. 

#!/usr/bin/perl
use strict;
use warnings;

my $greeting = "Hello World\n\n";
chomp $greeting;
print "greeting = $greeting";

 

And now when the script is run, there is no empty line.

[john.doe@localhost ]$ perl ~/testing.pl
greeting = Hello World
[john.doe@localhost ]$

 

The following character is used to represent a new line.

\n

 

On the other hand, let's say you have a variable where the new line is not at the end. In this scenario, chomp would not remove the new line.

#!/usr/bin/perl
use strict;
use warnings;

my $foo = "Line 1 \n Line 2";
chomp $foo;
print "foo = $foo";

 

This command will replace new lines with a comma.

$foo =~ s|\n|,|g;

 

Now, when you print $foo, the following should be displayed.

Line 1,Line 2

 

It's also probably a good idea to also do something with carriage returns.

$foo =~ s|\r\n|,|g;

 

And here is how you can replace new lines with the literal new line character \n.

$foo =~ s|\r\n|\\n|g;

 

Which should produce the following.

Line 1\nLine 2

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 5d6618 in the box below so that we can be sure you are a human.