我想我的程序通过的空间他们Perl程序用它们之间的空格分隔字符串?
之间
$string = "hello how are you";
分割字符串输出应该看起来像:
hello
how
are
you
我想我的程序通过的空间他们Perl程序用它们之间的空格分隔字符串?
之间
$string = "hello how are you";
分割字符串输出应该看起来像:
hello
how
are
you
你可以做,这是几种不同的方式。
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) = ...
@Array = split(" ",$string);
那么@Array
包含答案
你需要一个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
我认为像简单....
$string = "hello how are you";
print $_, "\n" for split ' ', $string;
拆分与正则表达式占多余的空格如有:
my $string = "hello how are you";
my @words = split /\s+/, $string; ## account for extra spaces if any
print join "\n", @words
我们也许可以读更好,如果它是不是全部**大胆的CAPS **。 – devnull
你做了什么研究?这是一个非常基本的要求。 –