0

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

$string = "hello how are you";  

输出应如下所示:

hello  
how  
are  
you
4

5 回答 5

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) = ...
于 2013-06-25T11:29:16.773 回答
4

我觉得很简单....

$string = "hello how are you";  
print $_, "\n" for split ' ', $string;
于 2013-06-25T11:27:01.110 回答
2

@Array = split(" ",$string);然后@Array包含答案

于 2013-06-25T10:58:08.480 回答
0

使用正则表达式拆分以考虑额外的空格(如果有):

my $string = "hello how are you";
my @words = split /\s+/, $string; ## account for extra spaces if any
print join "\n", @words
于 2013-06-25T13:31:05.687 回答
0

您需要一个拆分来将字符串除以空格,例如

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
于 2013-06-25T11:01:03.163 回答