Home: Perl Programming Help: Intermediate:
Accessing hash value from variable

New User

Jul 28, 2011, 9:00 AM

Views: 3344
Accessing hash value from variable

I have what I believe may be rather a unique instance. I have need to access a multidimensional hash value from a string. I have a proprietary xml configuration file that is parsed using XML::Simple, creating a multidimensional hash. The problem is that the the product nomenclaure doesn't align with the xml/hash structure, so our own nomenclature must be converted into a string to lookup the value in the hash. Here's an example:

Example hash snippet generated by XML::Simple (dumped by Data::Dumper):

$VAR1 = { 
'nw-version' => '',
'doc-version' => '1',
'folder' => {
'sys' => {
'instance' => 'folder',
'prettyName' => 'sys',
'folder' => {
'name' => 'config',
'config' => {
'compression' => {
'value' => '0',
'prettyName' => 'Compression'
'port' => {
'value' => '12345',
'prettyName' => 'Port'

Let's say I want to access the value $appliancecfg->{folder}{sys}{folder}{config}{port}{value}. The internal nomenclature our product uses (and thus this script) would access this at "/sys/config/port". I have written a sub that converts "/sys/config/port' to {folder}{sys}{folder}{config}{port}{value} (into a string called $absolutevalue), but the problem is I thus far have not been able to find a way access the data stored at $appliancecfg->{folder}{sys}{folder}{config}{port}{value} using $absolutevalue or its cousin $absolutestring (see example below).

I realize perl orthodoxy says you shouldn't do this, but in this case I explicitly need to do it in order to make this conversion work.

Here are some things I've tried:

This works (for testing):

print "Value = ".$appliancecfg->{folder}{sys}{folder}{config}{port}{value}."\n"; #this line works

This doesn't work (total crapshoot, I know):

$absolutestring = '$appliancecfg->{folder}{"sys"}{folder}{"config"}{port}{value}' 
$absolutevalue = '{folder}{"sys"}{folder}{"config"}{port}{value}'

print "Value = ".%$absolutestring."\n";
print "Value = ".$$absolutestring."\n";
print "Value = ".$absolutestring."\n";
print "Value = ".$appliancecfg->$absolutevalue."\n";
print "Value = ".$appliancecfg->$$absolutevalue."\n";
print "Value = ".$appliancecfg->{$absolutevalue}."\n";
print "Value = ".$appliancecfg->{$$absolutevalue}."\n";
print "Value = ".$appliancecfg{$absolutevalue}."\n";
print "Value = ".$appliancecfg{$$absolutevalue}."\n";

Can anyone help? Thanks!

Veteran / Moderator

Jul 28, 2011, 9:17 AM

Views: 3343
Re: [uhb] Accessing hash value from variable

See: perldoc -f eval

New User

Jul 28, 2011, 9:31 AM

Views: 3340
Re: [FishMonger] Accessing hash value from variable

Doh! That worked - I figured it would be something simple. Thanks!