一个Perl程序,它将String之间的空格分开?

use*_*656 0 perl split

我希望我的程序将字符串除以它们之间的空格

$string = "hello how are you";  
Run Code Online (Sandbox Code Playgroud)

输出应该如下所示:

hello  
how  
are  
you
Run Code Online (Sandbox Code Playgroud)

TLP*_*TLP 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///
Run Code Online (Sandbox Code Playgroud)

前两个创建具有单个单词的数组,最后一个创建不同的单个字符串.如果您想要的是打印的东西,那么最后就足够了.要打印数组,请执行以下操作:

print "$_\n" for @first;
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 通常,正则表达式捕获需要括号/(\S+)/,但是当使用/g修饰符并省略括号时,将返回整个匹配.
  • 以这种方式使用捕获时,您需要确保分配上的列表上下文.如果左手参数是标量,则会强制使用括号的列表上下文:my ($var) = ...