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 };
In reply to Re: How to split a non even number of string elements into a hash
by Eily
in thread How to split a non even number of string elements into a hash [RESOLVED]
by thanos1983
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |