in reply to How to access results of XML::Simple?

This looks familiar ... ;)

Have been introduced to Data::Dumper yet? Here is what it makes of the XML 'tree' that is built by XML::Simple:
use Data::Dumper; my $data = do {local $/;<DATA>}; my $xml = XMLin($data); print Dumper $xml;
Yields:
$VAR1 = {
   'label' => 'gene_of_interest',
   'id' => '3'
};
From this we see that label and id are the 'top level' keys, there is no 'gene' key. However, had the XML been a bit more proper ...
use strict; use warnings; use XML::Simple; my $data = do {local $/;<DATA>}; my $xml = XMLin($data); # ... and you use the correct syntax ;) print $xml->{gene}->{id}, "\n"; print $xml->{gene}->{label}, "\n"; __DATA__ <?xml version="1.0" ?> <genes> <gene id = "3" label = "gene_of_interest" /> </genes>
Then all is well. :)

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: (jeffa) Re: XML::Simple
by jdporter (Paladin) on Dec 18, 2002 at 01:08 UTC
    jeffa's (and PodMaster's) replies are correct, of course... but I want to stress that besides there being no 'gene' key, you can't do this:   print $xml->{'gene' => {'id', 'label'}}, "\n"; That will never work. It is syntactically bogus. Why did you think you could do that?
    You could do this:   print "$xml->{'gene'}{'id'}, $xml->{'gene'}{'label'}\n"; or even   print @{ $xml->{'gene'} }{'id','label'}, "\n"; assuming the data structure matches that.

    jdporter
    ...porque es dificil estar guapo y blanco.

      What?!?

      It is syntactically valid, it just won't do what he wants (no chance in hell).

      The expression will evaluate to $xml->{{}}, and that key (the stringified version of that anonymous hashref) is not defined, so a warning will be thrown.
      something like that ;)(actually $xml->{gene}{{}} , but it's not really important)

      If you didn't know what the comma operator would do in this expression, read "List" is a Four-Letter Word, as well as perldoc perlop

      update:

      use Data::Dumper; local $\="\n"; $a = { gene => { id => 3, label => 'generrrous' } }; print $a->{ gene, id}=1; print $a->{ gene => id }; print Dumper $a; __END__ 1 1 $VAR1 = { 'gene' => { 'label' => 'generrrous', 'id' => 3 }, 'gene‡˜id' => 1 };


      MJD says you can't just make shit up and expect the computer to know what you mean, retardo!
      ** The Third rule of perl club is a statement of fact: pod is sexy.

        If I want to access something nested within the gene tags. For example, <gene id = "1"><gene_seq id = "1"></gene_seq></gene>. How do I do that?

        print $xml->{gene_seq}{$id}{'startpos'}, "\n";
        Does not do it.