Thanks in advance for looking!

I have a string returned from a DB (Redis) that is pipe delimited and the individual items that are delimited are colon delimited

ex:

special:1001:area_code:617|special:1001:zip_code:02205|special:1001:dow:0|special:1001:tod:14

My goal is to convert these into a hash that looks like this (the first few sub-fields can be ignored):

{ area_code => 617, zip_code => 02205, dow => 0, tod => 14 }

I could write a loop no problem:

foreach my $little_string (split(/\|/,$big_string){ my @little_string_parts = split(/:/,$little_string); $result_hashref->{$little_string_parts[2]} = $little_string_parts[ +3]; }

that uses two splits though and I'm thinking a grep would be more efficient. Is there a way to iteratively progress through a string with a regex and use the matches to fill a hash? The below could work but it wouldn't account for the "big string" having a variable number of delimited members

$big_string =~ /special:[0-9]{4}:(.*):(.*)\|special:[0-9]{4}:(.*):(.*) +\|special:[0-9]{4}:(.*):(.*)\|special:[0-9]{4}:(.*):(.*)/; $result_hashref->{$1} = $2; $result_hashref->{$3} = $4; $result_hashref->{$5} = $6; $result_hashref->{$7} = $8;

Would a Map work here? I'm inexperienced with it but my thought is that it will only apply if we do a split on the initial string


In reply to Using a regex to replace looping and splitting by mwb613

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.