perl: using split and keeping split /regex/ in returned array elements

I want to split a string on keywords. The keywords match / [A-Z]+=/ (a space, the keyword in all caps, then an equal sign). While I want to split the string up into a nice, easy-to-use array, I need to keep the keyword with the array items. Or can I create an assoc array with the keywords as keys? That would be even better.

Thanks!

How about something like:



#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my $test = ' FOO=123 BAR=456 BAZ=789';
my $tmp = $test;
my %stuff;
while( $tmp =~ s/ ([A-Z]+)=(\w+)// ) { 
    $stuff{$1} = $2;
}

print Dumper \%stuff;


Or how about:



#!/usr/bin/perl -w

use strict;

use Data::Dumper;

my $str = " FOO=123 BAR=456 BAZ=789";
my @arr = split(/ ([A-Z]+)=/, $str);
# You have to start at index 1 because index 0 is everything
# before the first regex match
my %stuff = @arr[1 .. $#arr];

print Dumper \%stuff;

I just started learning perl so I’ll take another shot at it, in case you want positions too (otherwise a hash is definitely the way to go).



#!/usr/bin/perl -w

use strict;

use Data::Dumper;

my $str = " FOO=123 BAR=456 BAZ=789";
my @stuff;

foreach ( split(/\s/, $str) ) {
    if ( /([A-Z]+)=(\w+)/ ) {
        push @stuff, ([$1, $2]);
    }
}

print Dumper (\@stuff);


You saved the keyword using ([A-Z]+), but how did it get into %stuff? I mean, obviously @arr[1 … $#arr] does it, but what happens there?

Zowie, that’s pretty spiff.

split has a little known feature that causes capture-groups in the regex to also be returned along with the split pieces. From the perldoc:

So @arr will contain ( ‘’, ‘FOO’, ‘123’, ‘BAR’, ‘456’, ‘BAZ’, ‘789’ )

Whenever you have alternating keys and values in a list, you can just assign that to a hash. Though it’s a little prettier to say



shift @arr;
my %stuff = @arr;


Woo-hoo! That’s what I was looking for!