Why does Perl autovivify in this case?

六眼飞鱼酱① 提交于 2019-12-17 20:15:29

问题


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 = [];

回答1:


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);

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




回答2:


When you treat a scalar variable whose value is undef as any sort of reference, Perl makes the value the reference type you tried to use. In this case, $a has the value undef, and when you use @$a, it has to autovivify an array reference in $a so you can dereference it as an array reference.




回答3:


$a becomes an ARRAY reference due to Perl's autovivification feature.




回答4:


$a and $b are special variables in Perl (used in sort) and have a special scope of their own.

perl -MData::Dumper -e 'use strict; 1 for @$c; print Dumper $c'

produces

Global symbol "$c" requires explicit package name at -e line 1.
Global symbol "$c" requires explicit package name at -e line 1.
Execution of -e aborted due to compilation errors.


来源:https://stackoverflow.com/questions/2206836/why-does-perl-autovivify-in-this-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!