gpt4 book ai didi

string - 从 perl 变量中删除一个空格

转载 作者:行者123 更新时间:2023-12-04 08:58:22 27 4
gpt4 key购买 nike

我在进行简单的搜索和替换时遇到了很多麻烦。我尝试了提供的解决方案
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 环境中自动移动文件的某些方面,但有时文件名称中有空格,所以我想从变量中删除空格。

最佳答案

截至5.14 , Perl 提供了一个 non-destructive s/// option :

Non-destructive substitution

The substitution (s///) and transliteration (y///) operators now support an /r option that copies the input variable, carries out the substitution on the copy, and returns the result. The original remains unmodified.

my $old = "cat";
my $new = $old =~ s/cat/dog/r;
# $old is "cat" and $new is "dog"

This is particularly useful with map. See perlop for more examples.


所以:
my $hello_nospaces = $hello =~ s/\s//gr;
应该做你想做的。

关于string - 从 perl 变量中删除一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17330267/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com