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.

Seeking for Perl wisdom...on the process of learning...not there...yet!

In reply to How to split a non even number of string elements into a hash [RESOLVED] by thanos1983

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.