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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|