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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.