Perl chomp does not remove all the newlines

kamaci picture kamaci · Apr 13, 2011 · Viewed 14.9k times · Source

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?

Answer

Brian Roach picture Brian Roach · Apr 13, 2011

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;