1

我是 perl 的新手,我正在尝试根据一些用户输入创建一个哈希。我希望散列的键在每个键的增量的特定范围之间。此时我需要每个键的值为 0。

目前,我的代码是:

my %hash;
foreach (my $increm = $lowerbound; $increm <= $upperbound; ++$binsize) {

        push ($hash {$increm}, 0);

}

示例值可能是:

$lowerbound = 500
$upperbound = 600
$binsize = 1

我收到“不是数组引用”的错误,问题是什么,我哪里出错了?

先感谢您!

4

4 回答 4

3

首先,

++$binsize

应该

$increm += $binsize;

push有两种语法:

 push @array, LIST
 push $array_ref, LIST

您正在使用第二个,它需要对数组的引用,但您正在传递 undef 。使固定:

push $hash{$increm} ||= [], 0;

would do the trick. That said, that syntax is "highly experimental" and doesn't work with all reference to arrays. I suggest you stick to the traditional syntax.

push @{ $hash{$increm} ||= [] }, 0;

But thanks to autovivification, that simplifies to

push @{ $hash{$increm} }, 0;

But why are you using push at all? You only ever assign one value per key, so the push is equivalent to the following:

$hash{$increm} = [ 0 ];

Actually, it's questionable whether you want $hash{$increm} to be an array reference at all. Do you simply want the following?

$hash{$increm} = 0;
于 2013-10-31T13:34:44.147 回答
0

你推入阵列。只需使用这样的简单作业

$hash{$increment} = 0 ;

另外,不要在 $hash 结尾和花括号之间留空格。

于 2013-10-31T13:32:57.277 回答
0

你可以这样做:

perl -MData::Dumper -e 'for (1..5) { $a->{$_} = 0 }; print Dumper $a'

$VAR1 = {
          '4' => 0,
          '1' => 0,
          '3' => 0,
          '2' => 0,
          '5' => 0
        };
于 2013-10-31T13:34:03.083 回答
0

Push is for array, you can do it like this :

my %hash;

my $lowerbound = 500;
my $upperbound = 600;
my $binsize = 1;

foreach (my $increm = $lowerbound; $increm <= $upperbound; $binsize++) {
    $hash{$increm} = 0;
}
于 2013-10-31T13:36:43.547 回答