Search code examples
xmlperlperl-data-structures

generating hash table using perl script


I am trying to create hash table using perl. please can help me because i am begginer to perl and i am reading but i am not able to implement. i need to create hash table from below code data number as a key and description as value.


Solution

  • For a common data format like XML, don't try to do this manually by reading the file line by line and parsing it yourself. Instead, use a perl module to do it for you.

    The XML::Simple module may be sufficient for you to start with. I think the module is already installed on your system by default.

    use strict;   # tip: always use strict and warnings for safety
    use warnings;
    
    use Data::Dumper;
    use XML::Simple;
    
    my $data = XMLin(\*DATA); # loads up xml into a hash reference assigned to $data
    print Dumper $data;       # uses Data::Dumper to print entire data structure to console
    
    # the below section emulates a file, accessed via the special DATA file handle
    # but you can replace this with an actual file and pass a filename to XMLin()
    __DATA__
    <DATA>
        <!-- removed -->
    </DATA>
    

    UPDATE

    Now that the xml file is loaded into a hashref, you can access that hash and organise it into the structure that you want.

    # loads up xml into a hash reference assigned to $data
    my $data = XMLin(\*DATA);
    
    # organise into [testnumber => description] mappings
    # not sure if 'Detection' is what you meant by 'description'
    my %table = ( $data->{Testnumber} => $data->{Detection} );
    

    The problem with this scenario is that the xml data only contains a single testnumber, which is all this code handles. If you want to handle more than that, then you'll probably need to loop over an array somewhere. I don't know how the xml data will look like if there is more, so I don't know where the array will be.