I started with perl and XML at the same time and I well remember how confusing the syntax of hashes was back then. It gets easier fast. Hopefully the code below will help clarify things.

A few things to note.

You need a root node in your xml. (I used <genes></genes>), this allows you to treat multiple lines as part of a single data structure. The root name will not show up in the Data::Dumper output. You don't use this as part of the structure reference.

You can use a variable/or a hardcoded string in the hash references.

Data::Dumper is very useful for understanding the structure returned by XML::Simple. Don't try it on a very large file of XML because it will churn for ages then run out of memory. Use it on small samples and then comment it out before testing your code on a large file.

use strict; use warnings; use XML::Simple; use Data::Dumper; my $data = do {local $/;<DATA>}; my $xml = XMLin($data); print Dumper($xml), "\n\n"; for my $id (3,4) { print $xml->{gene}{$id}{'label'}, "\n"; } __DATA__ <?xml version="1.0" ?> <genes> <gene id = "3" label = "gene_of_interest" /> <gene id = "4" label = "Another_gene_of_interest" /> </genes>

Output

C:\test>220720 $VAR1 = { 'gene' => { '3' => { 'label' => 'gene_of_interest' }, '4' => { 'label' => 'Another_gene_of_interest' } } }; gene_of_interest Another_gene_of_interest C:\test>

Examine what is said, not who speaks.


In reply to Re: XML::Simple by BrowserUk
in thread How to access results of XML::Simple? by matth

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.