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

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:

use 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 };
Edit: added the output

Replies are listed 'Best First'.
Re^2: How to split a non even number of string elements into a hash
by AnomalousMonk (Archbishop) on Feb 09, 2017 at 18:20 UTC

    This approach has the advantage that it can, assuming the right constraints, handle an unpaired key at any position in the input string:


    Give a man a fish:  <%-{-{-{-<

Re^2: How to split a non even number of string elements into a hash
by thanos1983 (Parson) on Feb 09, 2017 at 14:34 UTC

    Hello Eily

    This is not a bad idea, but in cases that you will not need to parse a string beyond two elements at a time.

    I will keep that in mind for possible further implementations in future.

    Thank you for your time and effort reading and replying to my question.

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

      If the answer Athanasius gave you is easier to understand for you, it's the one you should use. Writing code that you can understand and modify by yourself should be your priority. But if you have trouble understanding what I did in my answer and are curious, feel free to ask for further details.

        Helllo again Eily,

        That is absolutely true on what you are saying but if we do not force our selfs to learn new things then we will end up in the same things and not expand our knowledge.

        This is why I love to post questions here and people can suggest new ideas for me to read on. :D

        Seeking for Perl wisdom...on the process of learning...not there...yet!
      This is not a bad idea, but in cases that you will not need to parse a string beyond two elements at a time.

      I don't understand this. Can you please explain "cases that you will not need to parse a string beyond two elements at a time"?


      Give a man a fish:  <%-{-{-{-<

        Hello AnomalousMonk,

        I miss understood when I quickly read the answer to my question. Thanks for clarifying.

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