我是Perl的新手。我试图找出如何打印数组哈希的大小。以下是我的代码片段。
my %map = (); // Initialization
while ($line = <>) {
chomp($line);
// Logic to split the $line
push( @{$map{$first_var}}, $rest );
}
// Print the amp
foreach my $value (sort keys %map) {
print "$value: @{$map{$value}}\n";
}
在打印时,我得到以下格式的输出
valA: (num1 num2 num3 num4)
valb: (num2 num4)
valC: (num1 num3 num4)
我希望确定每个键(valA,valB,valc)关联的元素数量。
我试过了:print "Number of nodes in the facility : scalar @{$map{$facility1}}\n";
但它以
的形式发出valA: scalar (num1 num2 num3 num4)
valb: scalar (num2 num4)
valC: scalar (num1 num3 num4)
我希望输出分别为valA,valB,valC显示4,2,3。我可能会误解,但标量提供了数组的长度。
由于
答案 0 :(得分:2)
您需要将print语句更改为:
print "Number of nodes in the facility : " . scalar(@{$map{$facility}}) . "\n";
答案 1 :(得分:2)
函数调用和表达式不在双引号字符串*中插值,因此您需要执行以下操作之一:
以下是每种技术的说明:
use strict;
use warnings;
my %hash = (
foo => [1, 2, 3],
bar => [qw(a b c d e f g)],
baz => [0 .. 99],
);
for my $key (keys(%hash)) {
# concatenation
print "Number of elements for $key: " . @{$hash{$key}} . "\n";
# temporary variable
my $count = @{$hash{$key}};
print "Number of elements for $key: $count\n";
# printf
printf("Number of elements for $key: %d\n", scalar(@{$hash{$key}}));
}
结果:
Number of elements for bar: 7
Number of elements for bar: 7
Number of elements for bar: 7
Number of elements for baz: 100
Number of elements for baz: 100
Number of elements for baz: 100
Number of elements for foo: 3
Number of elements for foo: 3
Number of elements for foo: 3
*有一个hack可以用来强行执行此操作,但它会严重阻碍代码的可读性,并且可能会导致代码的未来维护人员对你产生不良影响:
print "Number of elements for $key: ${\(scalar(@{$hash{$key}}))}\n";
使用数组引用的同等错误的等价物:
print "Number of elements for $key: @{[scalar(@{$hash{$key}})]}\n";