开发者

Perl chomp does not remove all the newlines

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜