开发者

Perl chomp does not remove all the newlines

开发者 https://www.devze.com 2023-02-25 13:42 出处:网络
I have code like: #!/usr/bin/perl use strict; use warnings; open(IO,\"<source.html\"); my $variable = do {local $/; <IO>};

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 s开发者_运维技巧till has newlines?


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;


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;


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消