7

我在进行简单的搜索和替换时遇到了很多麻烦。我尝试了 如何删除 Perl 字符串中的空格? 但无法打印。

这是我的示例代码:

#!/usr/bin/perl
use strict;
my $hello = "hello world";
print "$hello\n"; #this should print out >> hello world
#now i am trying to print out helloworld (space removed)
my $hello_nospaces = $hello =~ s/\s//g;
#my $hello_nospaces = $hello =~ s/hello world/helloworld/g;
#my $hello_nospaces = $hello =~ s/\s+//g;
print "$hello_nospaces\n"
#am getting a blank response when i run this.

我尝试了几种不同的方法,但我无法做到这一点。

我的最终结果是在 linux 环境中自动移动文件的某些方面,但有时文件名称中有空格,所以我想从变量中删除空格。

4

4 回答 4

19

You're almost there; you're just confused about operator precedence. The code you want to use is:

(my $hello_nospaces = $hello) =~ s/\s//g;

First, this assigns the value of the variable $hello to the variable $hello_nospaces. Then it performs the substitution operation on $hello_nospaces, as if you said

my $hello_nospaces = $hello;
$hello_nospaces =~ s/\s//g;

Because the bind operator =~ has higher precedence than the assignment operator =, the way you wrote it

my $hello_nospaces = $hello =~ s/\s//g;

first performs the substitution on $hello and then assigns the result of the substitution operation (which is 1 in this case) to the variable $hello_nospaces.

于 2013-06-26T21:00:35.120 回答
9

5.14开始,Perl 提供了一个非破坏性s///选项

无损替代

替换 ( s///) 和音译 ( y///) 运算符现在支持/r复制输入变量、对副本执行替换并返回结果的选项。原件保持不变。

my $old = "cat";
my $new = $old =~ s/cat/dog/r;
# $old is "cat" and $new is "dog"

这对于map. 有关perlop更多示例,请参阅。

所以:

my $hello_nospaces = $hello =~ s/\s//gr;

应该做你想做的。

于 2013-06-27T01:33:37.287 回答
4

You just need to add parentheses so Perl's parser can understand what you want it to do.

my $hello = "hello world";
print "$hello\n";

to

(my $hello_nospaces = $hello) =~ s/\s//g;
print "$hello_nospaces\n";

## prints 
## hello world
## helloworld
于 2013-06-26T21:00:49.077 回答
3

拆分这一行:

my $hello_nospaces = $hello =~ s/\s//g;

进入这两个:

my $hello_nospaces = $hello;
$hello_nospaces =~ s/\s//g;

来自官方Perl Regex 教程

如果匹配,则 s/// 返回进行的替换次数;否则返回false。

于 2013-06-26T20:58:17.453 回答