Reputation: 4095
I have a text file, its content as follows:
a b
c
and I use the below Perl code to substitute underscore '-' char at where ever the space char appears in the input line:
while (<>) {
$_ =~ s/\s/_/;
print $_;
}
and I get output like this:
a_b
c_
So my question is why Perl substitutes underscore in the place of newline '\n' char too which is evident from the input line which contains 'c'? When I use chomp in the code it works as expected.
Upvotes: 0
Views: 441
Reputation: 50637
\s
matches all white space chars [ \t\r\n\f]
, so use space if you want to replace plain spaces
$_ =~ s/ /_/g;
# or just
s/ /_/g;
Translation could also be used for such simple substitutions, eg. tr/ /_/;
Upvotes: 10