[tpm] Breaking a string up into hash keys
Olaf Alders
olaf.alders at gmail.com
Sun Apr 14 05:53:35 PDT 2013
> On Sat, 13 Apr 2013 10:33:27 -0400
> Antonio Sun <antoniosun at lavabit.com> wrote:
>
>> On Sat, Apr 13, 2013 at 1:29 AM, Digimer <lists at alteeve.ca> wrote:
>>
>>> Hi all,
>>>
>>> I've got a rather large, random-depth hash. ie:
>>>
>>> $conf->{foo}{bar} = "a";
>>> $conf->{baz} = "1";
>>> $conf->{this}{and}{the}{other}**{thing} = "what?";
>>>
>>> And so on. The number of hash keys can be quite varied, depending on the
>>> use.
>>>
>>> So now I want to be able to take a string that is in the format:
>>>
>>> foo::bar
>>> baz
>>> this::and::the::other::thing
>>>
>>> Split on the :: and use that to pull the value out of the hash.
>>>
You can just flatten the hash, switch the "::" with dots and look up the key that way.
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw( say );
use Data::Printer; # exports "p"
use Hash::Flatten qw( flatten );
my $conf;
$conf->{foo}{bar} = "a";
$conf->{baz} = "1";
$conf->{this}{and}{the}{other}{thing} = "what?";
my $flat = flatten( $conf );
my $key = 'this::and::the::other::thing';
$key =~ s/::/./g;
p $conf;
p $flat;
say $flat->{$key};
#######################################
olaf-alderss-macbook-pro.local[~/Documents/perl] $ perl flatten.pl
\ {
baz => 1,
foo => {
bar => "a",
},
this => {
and => {
the => {
other => {
thing => "what?",
},
},
},
},
}
\ {
baz => 1,
foo.bar => "a",
this.and.the.other.thing => "what?",
}
what?
--
Olaf Alders
olaf.alders at gmail.com
http://www.wundercounter.com
http://twitter.com/wundercounter
866 503 2204 (Toll free - North America)
416 944 8306 (direct)
More information about the toronto-pm
mailing list