0
$string = I am a boy

如何用下划线替换单词之间的空格?

4

4 回答 4

4

您需要一个正则表达式和替换运算符来做到这一点。

my $string = 'I am a boy';
$string =~ s/\s/_/g;

您可以在perlreperlretut中了解有关正则表达式的更多信息。一个很好的工具是Rubular


此外,您的代码将无法编译。您需要引用您的字符串,并且需要在末尾放置一个分号。

于 2013-03-28T10:30:24.467 回答
1
$string = 'I am a boy';
$string =~ s/ /_/g;
于 2013-03-28T10:30:14.477 回答
1
$string =~ tr( \t)(_);  # Double underscore not necessary as per Dave's comment
于 2013-03-28T11:22:38.217 回答
0

这只是为了在 perl 中显示另一个选项。 我认为Miguel Przimbabque展示了更聪明的方式,我个人遵循imbabque展示的方式。

my $str = "This is a test string";
$str =~ s/\p{Space}/_/g;
print $str."\n";

输出是

This_is_a_test_string
于 2013-04-20T18:27:45.317 回答