Search code examples
perlxml-simple

Perl: Accessing XML::Simple values in scalar context


Given the following XML::Simple object how would I copy one of the key values into a scalar assignment. The output below if from print Dumper($xmlobjectreturnedfrommodule);.

$VAR1 = {
          'Address2' => {},
          'City' => {},
          'EmailAddress' => {},
          'FName' => {},
          'PostalCode' => {},
          'LoginID' => {},
          'StateProvinceChoice' => {},
          'StateProvince' => {},
          'Phone' => {},
          'Country' => {},
          'Site' => {},
          'Address1' => {},
          'PhoneExt' => {},
          'LName' => {},
          'OrganizationName' => {},
          'Fax' => {}
        };

Normally with a hashref I would just using something like the following:

print $xmlobjectreturnedfrommodule->{'LoginID'};

but it is returning the following HASH(0x1e32640) instead of the keys value in the hashref. Is there something about XML::Simple that is causing this or am I missing something?


Solution

  • What you are doing is right. Check this:

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my $VAR1 = {
              'LoginID' => {},
            };
    
    print $VAR1->{LoginID};
    

    Output:

    HASH(0x8231818)
    

    the LoginID is pointing to a hash reference which is essentially empty. If you modify the code as below, then you will get an empty hash:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use Data::Dumper;
    
    my $VAR1 = {
              'LoginID' => {},
            };
    
    print Dumper ($VAR1->{LoginID});
    

    OutPut:

    $VAR1 = {};
    

    but it is returning the following HASH(0x1e32640) instead of the keys value in the hashref. Is there something about XML::Simple that is causing this or am I missing something?

    The way you are printing it (print $xmlobjectreturnedfrommodule->{'LoginID'};), it will never return keys/values of the hasref irrespective of whether the hashref is empty or not. It will always return something like HASH(0x1e32640) because that's what $xmlobjectreturnedfrommodule->{'LoginID'} is holding. In other words, {} is a hash reference.

    To print the keys/values, you need walk through the hash using a for loop and retrieve keys/values.