尝试修改不可创建的数组值,下标-2147483648

时间:2013-12-18 10:08:29

标签: perl integer-overflow

我是Perl的新手,所以忍受我......

我收到此错误:

  

尝试的非可创建数组值的修改,下标   -2147483648 at ...

来自此代码:

while (@data) {
    my $datum = shift @data;
    #print "adding $datum at $an\n";
    $mem[$an] = $datum;
    $an++;
    }
mem在这里声明:

@mem = ();

现在,当地址开始超过2G限制(0x80000000)时,问题会突然出现。所以这看起来与整数溢出有关,导致数字相互干扰为负。我如何告诉Perl我使用的是无符号32位整数?

由于

2 个答案:

答案 0 :(得分:2)

尝试使用push功能。

    while (@data) {
        my $datum = shift @data;
        #print "adding $datum at $an\n";
        push (@mem, $datum); ## this adds the new element at the end of the @mem array.
   }

要了解有关push的更多信息,请参阅here

如果您想使用hash,请使用以下代码:

my %mem = ();
while (@data) {
            my $datum = shift @data;
            #print "adding $datum at $an\n";
            $mem{$an} = $datum;
            $an++; ## Increment the key so as to avoid overwriting of the value.
}

答案 1 :(得分:2)

使用散列(关联数组),而不是数组。 Perl数组的设计不是很稀疏。

my %mem;
...
   $mem{$an} = $datum;