Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Perl autovivify in this case?

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 = [];
like image 666
Eugene Yarmash Avatar asked Dec 22 '22 05:12

Eugene Yarmash


2 Answers

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.

like image 95
daotoad Avatar answered Jan 09 '23 20:01

daotoad


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.

like image 25
brian d foy Avatar answered Jan 09 '23 20:01

brian d foy