G'day thanos1983,
Instead of using intermediary variables, you could do this:
my %hash = ((split / /, $str), $str =~ y/ / / % 2 ? () : undef);
I tested this on the command line. Sorry about the wrapping.
$ perl -wMstrict -MData::Dump -e 'my $s = "a 1 b 2 c 3 Odd"; my %h = ( +(split / /, $s), $s =~ y/ / / % 2 ? () : undef); dd \%h' { a => 1, b => 2, c => 3, Odd => undef } $ perl -wMstrict -MData::Dump -e 'my $s = "a 1 b 2 c 3 Even 4"; my %h += ((split / /, $s), $s =~ y/ / / % 2 ? () : undef); dd \%h' { a => 1, b => 2, c => 3, Even => 4 }
See "perlop: Quote-Like Operators" if you're unfamiliar with using y/// for counting.
— Ken
In reply to Re: How to split a non even number of string elements into a hash [RESOLVED]
by kcott
in thread How to split a non even number of string elements into a hash [RESOLVED]
by thanos1983
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |