[tpm] Solved! Re: Breaking a string up into hash keys

Digimer lists at alteeve.ca
Sun Apr 14 12:30:12 PDT 2013


On 04/13/2013 01:29 AM, Digimer 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.
>
> Any help would be much appreciated! :)
>

Thanks to everyone who responded! I've been only playing with perl for 
the last year or two, so some of the replies went over my head, I must 
admit. However, I was able to come up with a work-able solution;

====

use strict;
use warnings;

my $conf = {};
$conf->{string}{lang}{en_CA}{lang}{long_name} = "Canadian English";

my $key     = "string::lang::en_CA::lang::long_name";
my ($value) = _get_hash_value($conf, $key);
print "Key: [$key], value: [$value]\n";

sub _get_hash_value
{
	my ($conf, $key_string) = @_;
	
	my @keys      = split /::/, $key_string;
	my $last_key  = pop @keys;
	my $this_href = $conf;
	while (my $key = shift @keys)
	{
		$this_href = $this_href->{$key};
	}
	my $value = $this_href->{$last_key};
	
	return($value);
}

====

$ ./prog
Key: [string::lang::en_CA::lang::long_name], value: [Canadian English]

Again, thanks to all who responded!

-- 
Digimer
Papers and Projects: https://alteeve.ca/w/
What if the cure for cancer is trapped in the mind of a person without 
access to education?


More information about the toronto-pm mailing list