nepzraaz has asked for the wisdom of the Perl Monks concerning the following question:

I want to read from a xml file, the file looks like this:
$data = $xml->XMLin("data.xml"); # access XML data print "$data->{name} is $data->{age} years old.
But the problem is that the attribute "name" has to be stored in a variable. So I have to write the second line like this:
$name=$data->{name}; #reads the content of name print "$data->{$name} is $data->{age} years old.#goes to the value/att +ribute #pointed by $name
which is not working properly. I am using xml::simple to parse this file. Thanks for your suggestions.

Replies are listed 'Best First'.
Re: need help with xml parser
by sauoq (Abbot) on May 22, 2012 at 17:01 UTC

    It's impossible to debug your problem from the info given. You should double check the contents of $name. It is fine to do what you say you are doing, as this will show:

    $ perl -le '$h = {foo => "bar"}; $k = "foo"; print "$h->{$k}";' bar

    -sauoq
    "My two cents aren't worth a dime.";
Re: need help with xml parser
by Neighbour (Friar) on May 23, 2012 at 08:24 UTC
    If the name is in $data->{name} then your 2nd bit of code starts off right ($name = $data->{name}) but the print-command afterwards isn't. Try print "$name is $data->{age} years old.\n"
    Suppose $data->{name} contains the name 'Jos'. When you're storing that in $name, the print-statement tries to access $data->{Jos} which is very unlikely to exist in your XML-data. So your code probably doesn't print a name at all.