从perl变量中删除空格

M A*_*san 7 string variables perl whitespace

我在进行简单的搜索和替换时遇到了很多麻烦.我尝试了如何在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.
Run Code Online (Sandbox Code Playgroud)

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

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

mob*_*mob 19

你快到了; 你只是对操作符优先级感到困惑.您要使用的代码是:

(my $hello_nospaces = $hello) =~ s/\s//g;
Run Code Online (Sandbox Code Playgroud)

首先,这将变量的值赋给$hello变量$hello_nospaces.然后它执行替换操作$hello_nospaces,就像你说的那样

my $hello_nospaces = $hello;
$hello_nospaces =~ s/\s//g;
Run Code Online (Sandbox Code Playgroud)

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

my $hello_nospaces = $hello =~ s/\s//g;
Run Code Online (Sandbox Code Playgroud)

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


Sin*_*nür 9

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

非破坏性替代

substitution(s///)和transliteration(y///)运算符现在支持一个/r复制输入变量的选项,在副本上执行替换,并返回结果.原件保持不变.

my $old = "cat";
my $new = $old =~ s/cat/dog/r;
# $old is "cat" and $new is "dog"
Run Code Online (Sandbox Code Playgroud)

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

所以:

my $hello_nospaces = $hello =~ s/\s//gr;
Run Code Online (Sandbox Code Playgroud)

应该做你想做的事.


Vla*_*iev 3

分割这一行:

my $hello_nospaces = $hello =~ s/\s//g;
Run Code Online (Sandbox Code Playgroud)

进入这两个:

my $hello_nospaces = $hello;
$hello_nospaces =~ s/\s//g;
Run Code Online (Sandbox Code Playgroud)

来自官方Perl Regex 教程

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

  • 或者 `(my $hello_nospaces = $hello) =~ s/\s//g;`。不知道为什么我更喜欢这个,但它有点短。 (4认同)