我希望我的程序将字符串除以它们之间的空格
$string = "hello how are you";
Run Code Online (Sandbox Code Playgroud)
输出应该如下所示:
hello
how
are
you
Run Code Online (Sandbox Code Playgroud)
你可以这样做是几种不同的方式.
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///
Run Code Online (Sandbox Code Playgroud)
前两个创建具有单个单词的数组,最后一个创建不同的单个字符串.如果您想要的是打印的东西,那么最后就足够了.要打印数组,请执行以下操作:
print "$_\n" for @first;
Run Code Online (Sandbox Code Playgroud)
笔记:
/(\S+)/,但是当使用/g修饰符并省略括号时,将返回整个匹配.my ($var) = ...