string 如何替换perl中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5228788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:01:47  来源:igfitidea点击:

How to Replace white space in perl

perlstring

提问by DarRay

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

can i replace those two with

我可以用这两个代替吗

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

are there any difference? Please explain.

有什么区别吗?请解释。

回答by mattexx

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?

如果 $myString 存在,您的第一个代码将从 $myString 的末尾取一个换行符,然后删除所有“/”字符。第二行代码将删除所有空白字符。有错别字吗?

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.

如果这是问题,那么是的。由于换行符算作空格,第二个代码示例完成了上面两行的工作。

回答by Nikhil Jain

From perldoc chomp:

从 perldoc chomp

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

当您担心最终记录可能会丢失其换行符时,chomp从输入记录的末尾删除换行符。

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.

在段落模式下($/ = "" ),它会从字符串中删除所有尾随换行符。当处于 slurp 模式 ( $/ = undef) 或固定长度记录模式($/是对整数等的引用,请参阅 perlvar)时,chomp()不会删除任何内容。

you can removeleading and trailing whitespace from strings like,

您可以从字符串中删除前导和尾随空格,例如,

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

回答by Ben

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:

Chomp 将删除字符串末尾的换行符,但不会删除空格。典型的修剪函数使用以下两条替换行:

$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.

第一行删除字符串开头的所有空格,第二行删除字符串结尾之后的空格。