Perl 散列中的键数

Perl 散列中的键数,perl,Perl,我试图找出散列中的键数和值数,然后打印这些数字。我已经这样写了我的代码,但它没有给出键的数量。我的代码中有什么错误 #!/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"

我试图找出散列中的键数和值数,然后打印这些数字。我已经这样写了我的代码,但它没有给出键的数量。我的代码中有什么错误

#!/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" );
如何将这些num和datainfo存储在散列中?我如何计算散列中的键数?我试过这样做,但不起作用

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);
}
当我试图执行它时,它只给出一个数字,但我有更多的数字。也许我的哈希包含一个数字,但我如何迭代哈希来存储更多数字呢?

试试看

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" ); 
} 
并删除
my%nums=(“$number”、$info)

在执行while循环时,$number和$info每次都会覆盖它们自己。因此,您需要将该数据存储在while循环的散列中。

keys()
values()
都返回数组。在标量上下文中引用时,Perl中的数组返回数组的大小。因此,要获得散列中键或值的数量,只需在标量上下文中引用
keys()
values()
的结果:

# 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");
scalar keys %my_hash
# -or-
my $number_of_keys = keys %my_hash;
使用
%nums
数组:

my %nums = ( $number, $info );
print( "number of keys: ", scalar(keys(%nums)), "\n" ); # will print `1'
请注意,您的
%nums
哈希只有一个键值对,其中
$number
为键,
$info
为值。(声明
%nums
的一种更为传统和可读的方法是
my%nums=($number=>$info);

目标:我试图找出散列中的数字键和值的数量

这是对这个问题的一个直接回答

要获取哈希中的键数,请在标量上下文中应用
函数:

# 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");
scalar keys %my_hash
# -or-
my $number_of_keys = keys %my_hash;
值的数量将相同(尽管一个或多个值可能未定义)。您可以通过以类似方式应用
value
函数来证明这一点:

scalar values %my_hash
# -or-
my $number_of_values = values %my_hash;

你能提供输入数据的例子吗?等等,你在读卡器while循环中重新初始化了散列吗?是否也在同一循环中枚举它的内容?这令人困惑。听起来这些问题与您的问题没有任何关系,但它们导致您无法获得正确的输出。您在我的哈希中写入%nums我只有一个元素,因此如何在同一个哈希中迭代更多的数字,以隐藏哈希中的所有值。下面是一个示例:
对于我的$num(1..10){$nums{$num}=“info$num”}
<代码>%nums
现在看起来是这样的:
(1=>'info1',2=>'info2',…)
。然后,为了查看您有多少个键:
打印标量(键(%nums))
(将打印
10
)我如上所述进行了尝试,删除了行,删除了第二个while循环后,它还会打印每个数字和信息,之后每次递增时,都会在哈希中显示键的数量。比如1,2,3,…141。有没有可能打印出这样的密钥总数为141,而不是从1增加到141。还有,如果将我的第二个while循环连续执行无限次,则没有输出。@Andreyc您能提供输入数据、您得到的输出和所需输出的示例吗?