View Full Version : perl: using split and keeping split /regex/ in returned array elements
NoCoolUserName
02-01-2010, 05:23 PM
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!
friedo
02-01-2010, 06:09 PM
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;
Punoqllads
02-01-2010, 07:26 PM
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;
Pedro
02-01-2010, 08:29 PM
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);
NoCoolUserName
02-02-2010, 09:51 AM
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;
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.
friedo
02-02-2010, 10:12 AM
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 (http://perldoc.perl.org/functions/split.html):
If the PATTERN contains parentheses, additional list elements are created from each matching substring in the delimiter.
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;
NoCoolUserName
02-02-2010, 12:18 PM
split has a little known feature that causes capture-groups in the regex to also be returned along with the split pieces...Woo-hoo! That's what I was looking for!
vBulletin® v3.7.3, Copyright ©2000-2013, Jelsoft Enterprises Ltd.