Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Convert XML to Hash

by D'Femstar (Initiate)
on Mar 30, 2005 at 15:12 UTC ( [id://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 (Paladin) 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?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2024-09-18 08:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The PerlMonks site front end has:





    Results (24 votes). Check out past polls.

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.