如何在Perl中优雅地从字符串中分割成对的单词?

Ren*_*ger 3 perl

在perl中,我有一个粗略的字符串

my $str = "one  10 two   20   three    30";
Run Code Online (Sandbox Code Playgroud)

现在,我想将该字符串拆分为字数对,但没有成功.

我以为我能做到

my @pairs = split /([a-z]+[^a-z]+)/, $str;
Run Code Online (Sandbox Code Playgroud)

然后会有

$pairs[0] eq 'one  10 '
$pairs[1] eq 'two   20   '
$pairs[2] eq 'three    30'
Run Code Online (Sandbox Code Playgroud)

但是,我明白了

$pairs[0] eq ' '
$pairs[1] eq 'one  10 '
$pairs[2] eq ' '
$pairs[3] eq 'two   20   '
$pairs[4] eq ' '
$pairs[5] eq 'three    30'
Run Code Online (Sandbox Code Playgroud)

现在,我可以使用grep来获得我想要的结果:

my @pairs = grep {$_ =~ /\S/} split /([a-z]+[^a-z]+)/, $str;
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有一个更优雅的解决方案来解决这个问题.

bri*_*foy 15

为什么要把它们分成两对?只需获取一个单词列表,然后按两个单词表示.

 my @words = split /\s+/, $str;
 while( @words ) {
     my( $first, $second ) = splice @words, 0, 2;
     ...;
     }
Run Code Online (Sandbox Code Playgroud)

如果你想要一个哈希,它甚至更简单:

 my %pairs = split /\s+/, $str;
Run Code Online (Sandbox Code Playgroud)

我发现更容易理解并传递给另一个程序员而不是正则表达式.

  • 哈希不是开箱即用的.几乎任何时候有人说"配对",你应该听到"哈希":) (7认同)

Eug*_*ash 6

不知道它是否是一个优雅的解决方案,你可以使用与/g修饰符匹配:

my @pairs = $str =~ /(\w+\s+\d+)/g;
Run Code Online (Sandbox Code Playgroud)