4

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 = [];
brian d foy
  • 129,424
  • 31
  • 207
  • 592
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • 2
    Autovivification is discussed in the documentation at `perldoc -f exists` and `perldoc perlref` (also see http://perldoc.perl.org). – Ether Feb 05 '10 at 18:52
  • @Ether: I missed those examples in perldoc -f exists. Autovivification by "exists $ref->{key}" is surprising. – Eugene Yarmash Feb 05 '10 at 20:17

4 Answers4

8

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.

daotoad
  • 26,689
  • 7
  • 59
  • 100
3

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.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
  • 1
    Ok, here's another example: perl -MData::Dumper -e 'use strict; @$a;' Can't use an undefined value as an ARRAY reference at -e line 1. – Eugene Yarmash Feb 05 '10 at 12:26
  • 3
    Perl doesn't autovivify in that case. There's no one rule when it will kick in, but usually autovivify happens when you want to do something with the variable. There's no operation there. – brian d foy Feb 05 '10 at 12:47
0

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

Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
0

$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.
Ray Wadkins
  • 876
  • 1
  • 7
  • 16