Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Convert XML to Hash

by D'Femstar (Initiate)
on Mar 30, 2005 at 15:12 UTC ( #443495=perlquestion: print w/replies, xml ) Need Help??

D'Femstar has asked for the wisdom of the Perl Monks concerning the following question:

I want my program to access an XML file and extract an element and value of an attribute(done). the problem is there are 42 different keys. Each occurrence of the key has a different value everytime although sometimes a key might have the same value more than once. I want my program to allocate the values to the key it belongs and then count the number of occurrences of each value for each key. Anybody with a snippet of an idea?

2005-04-02 Edited by Arunbear: Changed title from 'Hash Browns', as per Monastery guidelines

Replies are listed 'Best First'.
Re: Convert XML to Hash
by Joost (Canon) on Mar 30, 2005 at 15:40 UTC
Re: Convert XML to Hash
by samizdat (Vicar) on Mar 30, 2005 at 16:06 UTC
    Store the values in an anon array as the value of the hash at that key. When you encounter a key,
    1. read the array at that value if it exists,
    2. push the new value onto the end of the array,
    3. then write it back to the value of the hash.
    The size of the anon array is the number of times that key appeared, and you can also easily extract the number of unique values.
      Actually, your step "2" is the only one that's necessary:
      # for a simple case, where input is just a "key value" list, and # when any key is repeated, we want to keep all its values in an array +: my %hash; while (<>) { my ( $k, $v ) = split; push @{$hash{$k}}, $v; } for my $k ( keys %hash ) { print "$k occurred ". scalar @{$hash{$k}} ." times\n"; }
      (update: but it seems like the OP really wants a hash-of-hashes, as suggested in the first reply above, rather than a hash-of-arrays.)
Re: Convert XML to Hash
by jdporter (Chancellor) on Mar 30, 2005 at 15:45 UTC
    How about some sample input and the corresponding desired ouput?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://443495]
Approved by Joost
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2022-05-27 14:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (95 votes). Check out past polls.

    Notices?