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

0 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;
}
Run Code Online (Sandbox Code Playgroud)

起初我写的就像那样

$all_lines[$free_locs[$rand_loc]] = &generate();
Run Code Online (Sandbox Code Playgroud)

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

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

感谢致敬,

特里

jwo*_*der 7

my @free_locs = {};声明@free_locs是一个单元素数组,其第一个元素是对空哈希({})的引用.因此,每当$rand_loc为0时,$insert_loc将是一个散列,并尝试使用该散列作为索引$all_lines[$insert_loc]产生错误.要声明@free_locs为空数组,请写入my @free_locs = ();或只是my @free_locs;.