Perl chomp does not remove all the newlines

15.4k Views Asked by At

I have code like:

#!/usr/bin/perl
use strict;
use warnings;
open(IO,"<source.html");
my $variable = do {local $/; <IO>};
chomp($variable);
print $variable;

However when I print it, it still has newlines?

3

There are 3 best solutions below

0
On BEST ANSWER

It removes the last newline.

Since you're slurping in the whole file, you're going to have to do a regex substitution to get rid of them:

$variable =~ s/\n//g;
0
On

Chomp only removes a newline (actually, the current value of $/, but that's a newline in your case) from the end of the string. To remove all newlines, do:

$variable =~ y/\n//d;
0
On

Or you can chomp each line as you read it in:

#!/usr/bin/perl

use strict;
use warnings;

open my $io, '<', 'source.html';
my $chomped_text = join '', map {chomp(my $line = $_); $line} <$io>;

print $chomped_text;