in reply to How to split a non even number of string elements into a hash [RESOLVED]
One other way to do it, which is to me a little more explicit, is to use m// in list context. This way you explicitly read your string two elements at a time. Since you will have as many elements in the return list as there are capture groups, even if they don't match, you can be sure to obtain an even sized list:
Edit: added the outputuse Data::Dumper; my $string = "one 1 two 2 three 3 odd"; my %hash = $string =~ / (\w+) # one captured word (?: # followed by \s(\d+) # a space and a captured number )? # in an optional non capturing gro +up /gx; print Dumper \%hash; __DATA__ $VAR1 = { 'three' => '3', 'two' => '2', 'one' => '1', 'odd' => undef };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to split a non even number of string elements into a hash
by AnomalousMonk (Archbishop) on Feb 09, 2017 at 18:20 UTC | |
|
Re^2: How to split a non even number of string elements into a hash
by thanos1983 (Parson) on Feb 09, 2017 at 14:34 UTC | |
by Eily (Monsignor) on Feb 09, 2017 at 19:27 UTC | |
by thanos1983 (Parson) on Feb 10, 2017 at 12:08 UTC | |
by AnomalousMonk (Archbishop) on Feb 09, 2017 at 18:07 UTC | |
by thanos1983 (Parson) on Feb 09, 2017 at 18:33 UTC |