为什么在这种情况下 Perl 会自动激活? [英] Why does Perl autovivify in this case?

查看:38
本文介绍了为什么在这种情况下 Perl 会自动激活?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 $a 会变成一个数组引用?我没有强迫它.

Why does $a become an arrayref? I'm not pushing anything to it.

perl -MData::Dumper -e 'use strict; 1 for @$a; print Dumper $a'
$VAR1 = [];

推荐答案

这是因为 for 循环将 @$a 的内容视为左值——你可以赋值给.请记住,for 将数组的内容别名为 $_.看起来,在 @$a 中寻找可别名内容的行为足以导致自动激活,即使没有要别名的内容也是如此.

It is because the for loop treats contents of @$a as lvalues--something that you can assign to. Remember that for aliases the contents of the array to $_. It appears that the act of looking for aliasable contents in @$a, is sufficient to cause autovivification, even when there are no contents to alias.

这种混叠效果也是一致的.以下内容也会导致自动激活:

This effect of aliasing is consistent, too. The following also lead to autovivification:

  • map {stuff} @$a;
  • grep {stuff} @$a;
  • a_subroutine(@$a);

如果你想管理自动激活,你可以使用同名pragma来实现词法控制.

If you want to manage autovivification, you can use the eponymous pragma to effect lexical controls.

这篇关于为什么在这种情况下 Perl 会自动激活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆