我希望我的程序将字符串除以它们之间的空格
$string = "hello how are you";
输出应如下所示:
hello
how
are
you
您可以通过几种不同的方式来做到这一点。
use strict;
use warnings;
my $string = "hello how are you";
my @first = $string =~ /\S+/g; # regex capture non-whitespace
my @second = split ' ', $string; # split on whitespace
my $third = $string;
$third =~ tr/ /\n/; # copy string, substitute space for newline
# $third =~ s/ /\n/g; # same thing, but with s///
前两个使用单个单词创建数组,最后一个创建不同的单个字符串。如果您只想打印一些东西,那么最后一个就足够了。要打印数组,请执行以下操作:
print "$_\n" for @first;
笔记:
/(\S+)/
,但是当使用/g
修饰符并且省略括号时,将返回整个匹配项。my ($var) = ...
我觉得很简单....
$string = "hello how are you";
print $_, "\n" for split ' ', $string;
@Array = split(" ",$string);
然后@Array
包含答案
使用正则表达式拆分以考虑额外的空格(如果有):
my $string = "hello how are you";
my @words = split /\s+/, $string; ## account for extra spaces if any
print join "\n", @words
您需要一个拆分来将字符串除以空格,例如
use strict;
my $string = "hello how are you";
my @substr = split(' ', $string); # split the string by space
{
local $, = "\n"; # setting the output field operator for printing the values in each line
print @substr;
}
Output:
hello
how
are
you