string – 从perl变量中删除空格

前端之家收集整理的这篇文章主要介绍了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.

原文链接:https://www.f2er.com/Perl/172184.html

猜你在找的Perl相关文章