I am trying to scan through a hash ref and get the value of certain elements (Regardless of the data structure).
Below is some sample code that will hopefully explain what I am trying to accomplish.
I have a data structure. I want to be able to get the value by just sending to a sub routine
my @return = &sub('Root->PersonA->Pets');
then it could send me back all the results for that locations. In the data below it would send back PetA and PetB. Notice the different structure between PersonA and PersonB. If I sent Root->PersonB->Pets I would get back PetAA and PetBB without having to change anything.
In the example below I convert everything to xml then use the XMLPAth to find the results. I do not think this is the best way but not sure how else to do it. Any ideas?
use Data::Dumper;
use XML::Simple;
use XML::XPath;
use XML::XPath::XMLParser;
my $perl_datastructure = {
Root =>
{
'PersonA' => {
Pets =>
[
PetA,
PetB,
],
},
'PersonB' =>
[
{
Pets => PetAA,
},
{
Pets => PetBB,
},
],
},
};
print Dumper($perl_datastructure);
$xmlstring = XMLout($perl_datastructure, NoAttr => 1, KeepRoot =>
+1);
#print $xmlstring;
my $xp = XML::XPath->new( xml => $xmlstring );
my $nodeset = $xp->find("//Root/PersonB/Pets");
foreach my $node ($nodeset->get_nodelist) {
my $perldata = XMLin( XML::XPath::XMLParser::as_string($node)
+);
print $perldata, "\n";
}
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.