我希望我的程序将字符串除以它们之间的空格
$string = "hello how are you";
输出应该如下:
hello
how
are
you
答案 0 :(得分:7)
你可以通过几种不同的方式来做到这一点。
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) = ...
答案 1 :(得分:4)
我觉得很简单......
$string = "hello how are you";
print $_, "\n" for split ' ', $string;
答案 2 :(得分:2)
@Array = split(" ",$string);
然后@Array
包含答案
答案 3 :(得分:0)
您需要split来将字符串除以
之类的空格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
答案 4 :(得分:0)
使用正则表达式进行拆分以考虑额外的空格(如果有):
my $string = "hello how are you";
my @words = split /\s+/, $string; ## account for extra spaces if any
print join "\n", @words