How to elegantly split word pairs from a string in Perl?

In perl, I have a line that looks something like

my $str = "one  10 two   20   three    30";

Now I would like to break this line into pairs of words and numbers, but there is no success.

I thought I could do

my @pairs = split /([a-z]+[^a-z]+)/, $str;

and then will be

$pairs[0] eq 'one  10 '
$pairs[1] eq 'two   20   '
$pairs[2] eq 'three    30'

However i get

$pairs[0] eq ' '
$pairs[1] eq 'one  10 '
$pairs[2] eq ' '
$pairs[3] eq 'two   20   '
$pairs[4] eq ' '
$pairs[5] eq 'three    30'

Now I can use grep for my desired result:

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

But I was wondering if there was a more elegant solution to this problem.

+3
source share
2 answers

I don’t know if this is an elegant solution, you can use match with modifier /g:

my @pairs = $str =~ /(\w+\s+\d+)/g;
+6
source

Why separate them as pairs? Just get a list of words, then take them in two.

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

If you need a hash, it's even simpler:

 my %pairs = split /\s+/, $str;

, , .

+15

Source: https://habr.com/ru/post/1734523/


All Articles