2

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?

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
kamaci
  • 72,915
  • 69
  • 228
  • 366
  • 19
    Next time ask yourself if you really think that a 10 year old feature of a mainstream language is really broken or if you're just using it wrong. – jiggy Apr 13 '11 at 19:23
  • 3
    [`select` isn't broken](http://www.google.com/search?q=select+isn%27t+broken) – Michael Myers Apr 13 '11 at 20:57

3 Answers3

18

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;
mscha
  • 6,509
  • 3
  • 24
  • 40
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
7

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;
ysth
  • 96,171
  • 6
  • 121
  • 214
2

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;
Joel Berger
  • 20,180
  • 5
  • 49
  • 104