Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: "Dynamically" Accessing a HoH

by djohnston (Monk)
on Jun 02, 2005 at 19:13 UTC ( #462995=note: print w/replies, xml ) Need Help??

in reply to "Dynamically" Accessing a HoH

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., 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 = ""; 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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://462995]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2021-06-19 21:50 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (93 votes). Check out past polls.