Hi thanos1983,

In the spirit of TIMTOWTDI: just yesterday I published some code that uses m/\G.../gc to incrementally parse a string into a hash. The goal of that code is to parse a string like "RH= 23.8 %RH T= 20.4 'C Td= -1.0 'C Tdf=-0.9 'C a=  4.2 g/m3   x=   3.5 g/kg  Tw= 10.2 'C ppm=  5635 pw=   5.68 hPa pws=  23.90 hPa h=  29.5 kJ/kg" (a line of data from a sensor I have to parse) into a data structure like { RH => { val=>23.8, unit=>"%RH" }, ... }. Although this is probably overkill for your case, note how it does allow for more powerful parsing of the input - in the aforementioned example, note how "ppm=  5635" doesn't have units, and how a simple split on whitespace won't work for "Tdf=-0.9".

If I apply the same principle to your code (slightly simplified):

use warnings; use strict; my $input = "one 1 two 2 three 3 odd_element"; my $REGEX = qr{ \s* \b (\w+) \s+ (\w+) \b \s* }msx; my %output; pos($input)=undef; while ($input=~/\G$REGEX/gc) { $output{$1} = $2; } my $rest = substr $input, pos $input; if (length $rest) { # leftovers $output{$rest} = 'turkeysandwich'; } use Data::Dumper; print Dumper(\%output); __END__ $VAR1 = { 'one' => '1', 'two' => '2', 'three' => '3', 'odd_element' => 'turkeysandwich' };

(Note: Assigning to pos is not needed in the example above, but it may become necessary if the code is embedded into a larger script that performs other regexes on the input that may modify pos.)

Hope this helps,
-- Hauke D


In reply to Re: How to split a non even number of string elements into a hash [RESOLVED] by haukex
in thread 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.