Hello monks,
I am trying to split a string based on white space elements and assign key value to a hash.
That would be easy if key value where even and not odd.
Sample of code:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $str = "one 1 two 2 three 3 odd_element"; my %hash = split / /, $str; print Dumper \%hash;
Sample of output:
Odd number of elements in hash assignment at test.pl line 7. $VAR1 = { 'three' => '3', 'one' => '1', 'odd_element' => undef, 'two' => '2' };
So I tried to split it into an array and the convert the array to a hash (overkill for no reason), but it gives the possibility to play with the array elements before assign it to hash.
Sample of code:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash; my $str = "one 1 two 2 three 3 odd_element"; my @array = split / /, $str; while (@array) { my $key = shift @array; my $value = shift @array; if (defined $key && defined $value) { $hash{$key} = $value; } else { $hash{$key} = undef; } } print Dumper \%hash;
Sample of output:
$VAR1 = { 'odd_element' => undef, 'one' => '1', 'two' => '2', 'three' => '3' };
It is working fine but there must be some internal function or another way to over come this overkill process.
So the question, is there any better way that I should come up with?
Thanks in advance everyone for their time and effort.
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |