Perl:使用引用" HASH(0x13bd718)"作为数组索引

时间:2014-08-20 20:35:28

标签: arrays perl reference

我正在编写一个脚本来实现游戏2048练习perl,并且会出现错误,如下所示:

在2048.pl第181行第11行使用引用“HASH(0x13bd718)”作为数组索引。

涉及的代码是这样的子程序:

sub gen1{
  my @free_locs = {};
  my $length;
  my $rand_loc;
  my $insert_loc;
  for ($i=0; $i<16; $i++){ 
    if($all_lines[$i] == 0){push @free_locs, $i;}
  }
  $length = @free_locs;
  $rand_loc = int rand $length;
  if ($rand_loc == $length) {$rand_loc--;}
  $insert_loc = $free_locs[$rand_loc];
  $all_lines[$insert_loc] = &generate();
  &row_update;
  &col_update;
}

起初我写的就像

一样
$all_lines[$free_locs[$rand_loc]] = &generate();

错误似乎更频繁地出现。然后我切换到上面显示的子程序中的代码,这似乎减少了它发生的机会,但它仍然发生......

我的编码方式有什么问题吗?编写这样一段代码的最简洁方法是什么?

谢谢和问候,

特里

1 个答案:

答案 0 :(得分:7)

my @free_locs = {};声明@free_locs是一个单元素数组,其第一个元素是对空哈希({})的引用。因此,只要$rand_loc为0,$insert_loc将是一个哈希值,并且尝试将该哈希值用作$all_lines[$insert_loc]中的索引会产生错误。要将@free_locs声明为空数组,请编写my @free_locs = ();my @free_locs;