Why does Perl autovivify in this case?

前端 未结 4 1295
清酒与你
清酒与你 2020-12-10 19:45

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


        
4条回答
  •  天命终不由人
    2020-12-10 20:34

    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.

提交回复
热议问题