How to replace space in perl

chomp($myString);
$myString =~ s/\///g;

Can I replace these two with

$myString =~ s/\s//g;

Is there any difference? Explain, please.

+3
source share
3 answers

Your first code will take a new line from the end of $ myString, if it exists, then remove all the "/" characters. The second line of code will remove all whitespace characters. Is there a typo?

You might want to know that you can replace this:

chomp($myString);
$myString =~ s/\s//g;

with this:

$myString =~ s/\s//g;

If this is a question, then yes. Since the newline character is considered a space, the second code example does the work of both lines above.

+9
source

From perldoc chomp :

chomp delete a new line from the end of the input record when you are worried that the last record may not have a new line.

($/ = "" ) . slurp ($/ = undef) ($/ , . Perlvar) chomp() .

,

$string =~ s{^\s+|\s+$}{}g
+1

Chomp will get rid of newlines at the end of your line, but will not remove spaces. A typical crop function uses the following two wildcards:

$string =~ s/^\s+//;
$string =~ s/\s+$//;

The first line removes any spaces at the beginning of the line, and the second removes spaces after the end of the line.

0
source

All Articles