Reputation: 61
I am trying to find out the number of keys and number of values in a hash and print those numbers. I've written my code like this but it has not given the number of keys. What is the error in my code?
#!/usr/bin/perl
use warnings;
use strict;
use XML::LibXML::Reader;
my $file;open $file, 'formal.xml');
my $reader = XML::LibXML::Reader->new( IO => $file ) or die ("unable to open file");
while ( $reader->nextElement( 'DATA' ) ) {
my $info = $reader->readOuterXml();
$reader->nextElement( 'Number' );
my $number = $reader->readInnerXml();
print( "num: $number\n" );
print( " datainfo: $info\n" );
How can I store these num and datainfo in a hash? And how can I count number of keys in hash? I tried like this but it is not working.
my %nums =( "$number", $info);
while ((my $keys, my $values) = each (%nums)) {
print ("NUMBER:$keys." =>"INFORMATION: ".$values." \n");
}
my $key_count = keys %nums;
print "$key_count";
}
close($file);
}
When I am trying to execute it, it gives only one number, but I have more numbers. Maybe my hash contains one number, but how can I iterate my hash to store more numbers?
Upvotes: 2
Views: 9092
Reputation: 19427
Goal: I am trying to find out numbers keys and number of values in hash.
Here is a direct answer to this question in general.
To obtain the number of keys in your hash, apply the keys
function in a scalar context:
scalar keys %my_hash
# -or-
my $number_of_keys = keys %my_hash;
The number of values will be identical (although one or more values may be undefined). You can prove this by applying the values
function in a similar fashion:
scalar values %my_hash
# -or-
my $number_of_values = values %my_hash;
Upvotes: 1
Reputation: 1735
keys()
and values()
both return arrays. When referenced in scalar context, arrays in Perl return the size of the array. So, to get the number of keys or values in your hash, just reference the result of keys()
or values()
in scalar context:
# prints the number of keys
print( scalar(keys(%hash)), "\n" );
print( keys(%hash) . "\n" );
# prints the number of values
print( scalar(values(%hash)), "\n" );
print( values(%hash) . "\n");
Using your %nums
array:
my %nums = ( $number, $info );
print( "number of keys: ", scalar(keys(%nums)), "\n" ); # will print `1'
Note that your %nums
hash has only one key-value pair with $number
as the key and $info
as the value. (A more conventional and readable way to declare %nums
would be my %nums = ( $number => $info );
)
Upvotes: 7
Reputation: 1818
try
my %nums;
while ( $reader->nextElement( 'DATA' ) ) {
my $info = $reader->readOuterXml();
$reader->nextElement( 'number' );
my $number = $reader->readInnerXml();
$nums{$number} = $info;
print( "num: $number\n" );
print( " datainfo: $info\n" );
}
and remove my %nums =( "$number", $info);
When you do your while loop, your $number and $info overwrite themselves each time. So you need to store that data in the hash in the while loop.
Upvotes: 2