从Perl变量中删除空格

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环境中文件移动的某些方面,但有时文件名中会有空格,因此我想从变量中删除空格。


1
另外,Linux和许多其他操作系统完全支持文件名中的空格,只要开发人员小心即可。删除空格可能会产生不良影响,例如在"helloworld.txt"和"hello world.txt"之间创建歧义。 - Rob I
1
谢谢大家的快速回复。我一直在尝试在s和g之间更改语法。 很抱歉我不能投票,因为我没有15个声望点数。 - M Alhassan
4个回答

19

你已经快要成功了,你只是对操作符优先级感到困惑。你需要使用的代码如下:

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

首先,将变量$hello的值分配给变量$hello_nospaces。然后对$hello_nospaces执行替换操作,就好像您说过的一样。

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

由于绑定运算符=~的优先级高于赋值运算符=,所以您编写的方式

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

首先对$hello执行替换操作,然后将替换操作的结果(在本例中为1)赋值给变量$hello_nospaces


非常感谢。我以为只是语法错误。 你的解释非常清晰,现在我明白了。谢谢。 - M Alhassan
1
很明显,这位用户没有优先级问题,而是遇到了原地替换的问题,即该用户认为 s// 返回一个新字符串。 - 7stud

9

从 Perl 5.14 版本开始,提供了一个非破坏性的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;

应该做你想要的事情。

4
你只需要添加括号,这样Perl的解析器就可以理解你想要它做什么了。
my $hello = "hello world";
print "$hello\n";

to

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

## prints 
## hello world
## helloworld

3

分割这行:

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

进入那两个:

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

来自官方Perl正则表达式教程:

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


4
或者 (my $hello_nospaces = $hello) =~ s/\s//g;。不确定为什么我更喜欢这个,但它稍微短一点。 - Rob I

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接