I used to do something similar, but I eventually adopted a unique syntax for traversing structures when my requirements grew to include array traversal. My solution (which may be overkill for your needs) involves dot and colon meta characters - the dot represents a hash key (e.g. depTar.name), and the colon represents an array element (e.g. foobar:0). This works great unless you expect to have hash keys that might contain dot or colon characters, in which case support for escaped meta characters is required. I've been working on a module that uses this scheme for quite some time now (see my home node for the url).
sub lookup {
my( $ref, $str ) = @_;
return $ref unless length $str;
my( $v, $r, $arr );
while ( $str =~ s/^((?:[^\\]|\\.)*?)([:.])//o ){
$r = $2;
( $v = $1 ) =~ s/\\([.:\\])/$1/og;
$ref = $arr ? $ref->[$v] : $ref->{$v};
$arr = $r eq ':';
}
$str =~ s/\\([.:\\])/$1/g;
return $arr ? $ref->[$str] : $ref->{$str};
}
my $usr_str = "depTar.name";
my $xml = { 'depTar' => { 'name' => 'c_p20', 'loc' => 'srvr1' }};
print lookup( $xml, $usr_str ); # c_p20
Note: This code snippet was modified slightly to exclude elements which are irrelevant to this discussion (hopefully I didn't break anything in the process). I should probably also point out that it will (by design) traverse blessed references.