in reply to How to split a non even number of string elements into a hash [RESOLVED]
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to split a non even number of string elements into a hash [RESOLVED]
by thanos1983 (Parson) on Feb 10, 2017 at 12:10 UTC |