我试图将字符串拆分为多个单词(其中一个单词具有特殊字符$
),但是拆分无效。我想将下面的字符串拆分为“测试”“ Str $ ing”
$test = "Test Str$ing";
my @words = split(" ",$test);
print "@words";
print "-------1End------------\n";
foreach my $str (split /(\s)+/, $test) {
print "$str\n";
}
print "-------End------------\n";
我执行了上面的代码,并得到了下面的结果,如您所见,第二个单词在那里只有一半:
Test Str
-------1End------------
Test
Str
-------End------------
有什么帮助吗?
在Perl中,双引号字符串中的美元符号会触发插值。所以这个任务:
$test = "Test Str$ing";
设置$test
为字符串,Test Str
后跟变量的值$ing
。如果$ing
未设置(并且您没有启用约束,这将导致程序在此时失败),则结果为just Test Str
。
要获得字面的美元符号,您必须使用反斜杠将其转义,或者使用单引号代替:
$test = "Test Str\$ing";
# or
$test = 'Test Str$ing';
#!
无论如何,无论如何,程序的第一行应该是use strict;
。然后,Perl会捕捉到这些错误并将其炸掉,而不是让您默默地射击自己。为了达到良好的效果,您还应该添加use warnings;
:
#!/usr/bin/env perl
use strict;
use warnings;
$test = "Test Str$ing";
观察当我尝试运行以上命令时会发生什么:
Global symbol "$test" requires explicit package name (did you forget to declare "my $test"?) at foo.pl line 5.
Global symbol "$ing" requires explicit package name (did you forget to declare "my $ing"?) at foo.pl line 5.
Execution of foo.pl aborted due to compilation errors.
您的程序应该看起来更像这样,只需进行最小的更改即可通过:
#!/usr/bin/env perl
use strict;
use warnings;
my $test = 'Test Str$ing';
my @words = split ' ', $test;
print "@words";
print "-------1End------------\n";
foreach my $str (split /(\s)+/, $test) {
print "$str\n";
}
print "-------End------------\n";
这对我来说仍然很奇怪,因为您将所有单词打印在一行中,而在1End
前哨之前没有换行符,然后将每个单词打印在一行之间,并用空白行(但不是真正的空白-包含原始字符串)。但是,如果这就是您想要的,则上面的方法有效。输出:
Test Str$ing-------1End------------
Test
Str$ing
-------End------------
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句