mwb613 has asked for the wisdom of the Perl Monks concerning the following question:
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:14My 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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Using a regex to replace looping and splitting
by tybalt89 (Monsignor) on Jan 24, 2018 at 00:18 UTC | |
by mwb613 (Beadle) on Jan 24, 2018 at 01:20 UTC | |
by Cristoforo (Curate) on Jan 24, 2018 at 02:55 UTC | |
Re: Using a regex to replace looping and splitting
by AnomalousMonk (Archbishop) on Jan 24, 2018 at 03:42 UTC | |
Re: Using a regex to replace looping and splitting
by johngg (Canon) on Jan 24, 2018 at 12:07 UTC | |
Re: Using a regex to replace looping and splitting
by tybalt89 (Monsignor) on Jan 24, 2018 at 13:14 UTC | |
Re: Using a regex to replace looping and splitting
by Laurent_R (Canon) on Jan 24, 2018 at 07:26 UTC | |
Re: Using a regex to replace looping and splitting
by pwagyi (Monk) on Jan 24, 2018 at 04:15 UTC |