我在进行简单的搜索和替换方面遇到了很多麻烦.我试过提供的解决方案
How do I remove white space in a Perl string?
但无法打印出来.
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.
我尝试了几种不同的方法,但我无法做到这一点.
解决方法
你快到了;你只是对操作符优先级感到困惑.您要使用的代码是:
(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.jb51.cc/Perl/172184.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。