How to Replace white space in perl

2020-03-05 06:37发布

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

can i replace those two with

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

are there any difference? Please explain.

标签: perl string
3条回答
贪生不怕死
2楼-- · 2020-03-05 07:05

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

Maybe you want to know you can replace this:

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

with this:

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

If that's the question, then yes. Since a newline counts as whitespace, the second code example do the job of both lines above.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-03-05 07:06

Chomp will get rid of newlines at the end of your string, but won't remove whitespace. A typical trim function uses the following two substitution lines:

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

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

查看更多
祖国的老花朵
4楼-- · 2020-03-05 07:16

From perldoc chomp:

chomp remove the newline from the end of an input record when you're worried that the final record may be missing its newline.

When in paragraph mode ($/ = "" ), it removes all trailing newlines from the string. When in slurp mode ($/ = undef ) or fixed-length record mode ($/ is a reference to an integer or the like, see perlvar) chomp() won't remove anything.

you can remove leading and trailing whitespace from strings like,

$string =~ s{^\s+|\s+$}{}g
查看更多
登录 后发表回答