string – 从perl变量中删除空格

我在进行简单的搜索和替换方面遇到了很多麻烦.我试过提供的解决方
How do I remove white space in a Perl string?
但无法打印出来.

这是我的示例代码

#!/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环境中移动文件的某些方面,但有时文件名称中有空格,所以我想从变量中删除空格.

解决方法

你快到了;你只是对操作符优先级感到困惑.您要使用的代码是:
(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.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...