2013-06-25 106 views
0

我想我的程序通过的空间他们Perl程序用它们之间的空格分隔字符串?

之间

$string = "hello how are you"; 
分割字符串输出应该看起来像:

hello 
how 
are 
you 
+3

我们也许可以读更好,如果它是不是全部**大胆的CAPS **。 – devnull

+1

你做了什么研究?这是一个非常基本的要求。 –

回答

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

我不明白为什么有人会为此付出代价。这是来自TLP的大部分时间的一流答案。 – simbabque

+0

@simbabque谢谢你,这很好听。 :) – TLP

+0

@TLP:fyi,我没有downvote,你的回答看起来很完美。 –

2

@Array = split(" ",$string);那么@Array包含答案

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 
+0

我觉得有一点解释会让这个答案更好。 – simbabque

+0

@匿名用户:任何原因来回downvote? –

+0

我没有downvote,但我怀疑原因是:你应该'使用警告',你不应该分裂在一个单一的空白,除非你设计要空字段的情况下连续多个空格,使用块打印是有效的代码,但看起来很奇怪,'$,'对某些人来说可能是模糊的,而for循环更具可读性。 – TLP

4

我认为像简单....

$string = "hello how are you"; 
print $_, "\n" for split ' ', $string; 
0

拆分与正则表达式占多余的空格如有:

my $string = "hello how are you"; 
my @words = split /\s+/, $string; ## account for extra spaces if any 
print join "\n", @words 
相关问题